Abdullah Nurum Abdullah Nurum - 3 months ago 12
Swift Question

How to call this in another view

I have

func
for post request in Library.swift. I am calling it from register.swift. It is sending data to server, but I could not get data from Library.swift to my view. How to solve this?

Library().sendRegisterInfo("http://tsprphones.com/php4credit/AddNewUser.php", postData: "emailAddressOK=" + emailAdd + "&passwordOK=" + password + "&registeredTimeOK=" + LocalTimeString + "&firstNameOK=" + firstName + "&middleNameOK=" + middleName + "&lastNameOK=" + lastName){ result in
print(result)//this should be result from server but is not working.
}


This is func in my Library.swift

func sendRegisterInfo(url:String, postData: String, completion: String -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
let postString = postData
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let needToPassToAnother = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String

print(needToPassToAnother)//this printing is good
}
task.resume()
}

Answer

In sendRegisterInfo method, you did not set any string to the completion block, this explains why it does not print anything in the console.

func sendRegisterInfo(url:String, postData: String, completion: String -> Void) {
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = "POST"
    let postString = postData
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")   
            return
        }
        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)") 
        }
      let needToPassToAnother = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String

        print(needToPassToAnother)//this printing is good
    }
    completion("It Works")
    task.resume()
}

It should print "It Works" in your ViewController class when you call sendRegisterInfo method.

Besides, you should consider using a singleton to call all your API.