I'm trying to figure out why this code takes so long to log in. It currently works, but it's just really really slow. My console shows that it's receiving the success response right away but it still doesn't go to the next view controller for awhile. I also found that after I added the code to dismiss the loading indicator it immediately closes too. So right now if I provide proper credentials it will close the loading indicator but still wait like 15 seconds before going to the next view controller. Ideas?
let request = NSMutableURLRequest(URL: NSURL(string: "myurl")!)
request.HTTPMethod = "POST"
var postString = "user=\(username.text)&pass=\(password.text)"
var success = 0
var alert = UIAlertView(title: "Logging In", message: "Please wait...", delegate: self, cancelButtonTitle: "Cancel");
var loadingIndicator = UIActivityIndicatorView(frame: CGRectMake(50, 10, 37, 37)) as UIActivityIndicatorView
loadingIndicator.center = self.view.center;
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
loadingIndicator.startAnimating();
alert.setValue(loadingIndicator, forKey: "accessoryView")
loadingIndicator.startAnimating()
alert.show();
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
let alert = UIAlertView()
alert.title = "Login Failed!"
alert.message = "Error: \(error)"
alert.delegate = self
alert.addButtonWithTitle("OK")
alert.show()
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
println("responseString = \(responseString)")
let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: nil) as! NSDictionary
success = jsonData["Success"] as! Int
if(success == 1){
alert.dismissWithClickedButtonIndex(0, animated: true)
self.login()
}
else{
let alert = UIAlertView()
alert.title = "Login Failed"
alert.message = "Invalid username/password"
alert.delegate = self
alert.addButtonWithTitle("Retry")
alert.show()
}
}
task.resume()