Avinash Mulewa Avinash Mulewa - 4 months ago 17
Swift Question

animateWithDuration call after a long time when it is written in URLSession

In Swift 2.0, I am using a web API to upload and download some data. Before calling the API, I have started an activity indicator animation and want to stop it when the response of the API has come.

However, when I want to stop the animation after the API response, the indicator stops after a long time of wait.

Here is my code:

let activityIndi = UIActivityIndicatorView(activityIndicatorStyle: .White)
activityIndi.startAnimating()
flagBtn.addSubview(activityIndi)
let urlString = NSURL(string: "URL")
NSURLSession.sharedSession().dataTaskWithURL(urlString!, completionHandler: { (data: NSData?, _, _) -> Void in
if data != nil {
do {
let jsonInfoDic = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! [String:AnyObject]
if(jsonInfoDic["status"] as! Bool)
{
UIView.animateWithDuration(1.0, animations: {
activityIndi.stopAnimating()
}, completion:{ (finished: Bool) -> Void in
})
}
}
catch { print("Exception in parsing JSON.\n\nReason: \(error)") }
}
}).resume()

Answer

You need to perform UI-modifying operations on the main thread. Since the callback of dataTaskWithURL:completionHandler: is performed on a background thread (NSURLSession thread), you must dispatch the UI code as follows:

dispatch_async(dispatch_get_main_queue()) {
    activityIndi.stopAnimating()
}

Furthermore, I suspect you won't need UIView.animateWithDuration:completion: because stopAnimating performs an animation by itself.

Comments