Kyle Fernandes Kyle Fernandes - 4 months ago 18
Swift Question

Alert displaying late while getting response from URL

Im trying to display an alert when a user presses a button to insert text in database, everything works fine but when i get the response and try to display it in alert, it doesn't work instantly, the alert is displayed when i press somewhere on the screen, after pressing the button. I need it to come as soon as the button is pressed , if i print the same response it works fine, but when i use alert it doesn't.

@IBAction func posting(sender: AnyObject) {


let request = NSMutableURLRequest(URL: NSURL(string: "https://example.com/appapi/test2.php")!)
request.HTTPMethod = "POST"
let postString = "a=\(title.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error inenter code here

if error != nil {
print("error=\(error)")
return
}
let responseString = "\(NSString(data: data!, encoding: NSUTF8StringEncoding)!)"
self.displayR(responseString)


}
task.resume()





}
func displayR(str:String){

var alert = UIAlertController(title: "Description", message: "\(str)" ,preferredStyle: .Alert)


alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in }))

self.presentViewController(alert, animated: true, completion: nil)

}

Answer

When you execute data task with request, the code executes in a background thread. Any UI changes (in this case displaying alert) must be done on main thread. To do so put your call to display function in following code:

dispatch_async(dispatch_get_main_queue()) {
//call display function here 
}
Comments