Search code examples
iosnsnotificationcenteruiactivityindicatorviewnsthread

iOS: how to properly stop an Activity Indicator?


I'd like to stop the animation of the indicator within a method called by default NSNotificationCenter with a postNotificationName. So I'm doing this on Main Thread

-(void)method
{
    ...
    [ind performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
}

It does'n work. Method is called correctly, any other called selectors do their job but not stopAnimating. I put [ind stopAnimating] in another function and then called it via performSelectorOnMainThread but it still didn't worked.


Solution

  • You can also use the below method which starts and stops the activity indicator on main thread in a single method, also provides you to execute your code asynchronously as well-

    - (void)showIndicatorAndStartWork
    {
        // start the activity indicator (you are now on the main queue)
        [activityIndicator startAnimating];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // do your background code here
    
            dispatch_sync(dispatch_get_main_queue(), ^{
                // stop the activity indicator (you are now on the main queue again)  
            [activityIndicator stopAnimating];
            });
        });
    }