If you want the application to respond by performing some kind of heavy task, you will need to execute it in the background thread.
This is roughly what happens here: the main thread of your application runs in a launch loop. At the beginning of each iteration of the loop, iOS checks for any events (for example, user interaction, changes in view due to animation, running timers, etc.), then queues up many methods that need to be executed. Then iOS executes and executes each of these methods, and then when everything is complete, it updates the display. Then iteration of the next loop cycle begins. Updating the display is expensive, so iOS cannot do this after each line of code has been executed.
So, with your code, when you specify the ActivityInicator startAnimating function, it tells iOS that at the end of each iteration of the run loop, the activity indicator image should be updated to the next image in the animation sequence. Then, before iOS reaches the end of the current iteration of the run loop, you call stopAnimating, which tells iOS that it no longer needs to refresh images. So basically you say that he should stop before he even starts.
You can use Grand Central Dispatch to easily run code in another thread. It is important to note that any updates to the user interface must be performed in the main thread.
func heavyWork() { self.activityIndicator.startAnimating() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // Do heavy work here dispatch_async(dispatch_get_main_queue()) { // UI updates must be on main thread self.activityIndicator.stopAnimating() } } }
Also note that with asynchronous programming, for example, in the example above, you cannot return a value from the asynchronous section of the method that called it. For instance. in the above example, you cannot return the result of hard work from the heavyWork () method. This is because the function assigns the asynchronous code to run on another thread and returns immediately so that it can continue the current iteration of the run loop.
source share