I have the following code which performs a login to a web server, retrieves an API token, and then allows the app to continue. After this code executes, the the calling function uses the login_result to report to the user whether they successfully logged in or need to try again.
Right now, I just have the app sleep for 3 seconds to make sure I have response before moving on. Otherwise, the login results handler starts executing without an answer (because the server hasn't had time to respond).
Obviously, this is a horrible way to do things. What is the correct / swift idiomatic way to handle this?
func remote_login (email: String, password: String) -> Bool {
login_result = false
var jsonResults: NSDictionary = [:]
let account = Account()
let url = NSURL(string: "\(base_api_url())/login?email=\(email)&password=\(password)")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do {
jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
account.setCredentials(jsonResults) // we store an API token returned from a successful login; we don't store the users credentials locally
self.login_result = true
}
catch {
print("\n\n\n Login Error \n\n\n")
}
}) // task
task.resume()
sleep(3) //need time for the response to come back...s/b far more elegant way to do this.
return self.login_result
}