Any help would be appreciated, I have a bunch of classes that used to call the NSURLConnection Synchronous method, but that does not exist anymore. How do I call this block of code in a way that waits for the response before it moves on?
class func login(email:String,password:String)->Int{
var userId = 0
let postEndpoint:String = "https://www.testsite.com/user/login.php"
let url = NSURL(string: postEndpoint)!
let urlRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
urlRequest.HTTPMethod = "POST"
let body = "email=\(email)&password=\(password)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
urlRequest.HTTPBody = body
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest) {(data, response, error) in
if data != "" && error == nil{
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
if let id = json["id"] as? Int {
print("found id:\(id)")
userId = id
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
userId = 2
}
}
else{
userId = 2
}
}
task.resume()
return userId
}
And the code calling this...
success = User.login(emailTextField.text!, password: passwordTextField.text!)
print("success last: \(success)")
The problem is the "success last:" is called before the user id is returned. Aaarrrrgggghhhhh!