Tolga Taner Tolga Taner - 4 months ago 7
Swift Question

Loading Indicator is not working correctly

This is my code. I want to show an indicator when I click the button during passing data and adding data to database. How can I fix it?

@IBAction func addWishList(sender: AnyObject) {

self.loading.startAnimating()

addMovie(showMovie!) // Database add method.

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {



dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in

let controller : WishListViewController = segue.destinationViewController as! WishListViewController

if segue.identifier == "segue" {

controller.user = self.tmpUser // data from Facebook to pass another controller

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.loading.stopAnimating()

})


}
})
}

Answer

Your addMovie blocking main queue. You need to give some delay to add it to next run loop. Try using:

@IBAction func addWishList(sender: AnyObject) {
    self.loading.startAnimating()
    //This will add to next main run loop.
    let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_SEC))) 
    dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
            addMovie(showMovie!) // Database add method.

    })
}