How can I create a activity indicator in middle of view programmatically?

Piscean picture Piscean · Feb 24, 2011 · Viewed 62.7k times · Source

I am working with an app which parses an feed online. When I click the refresh button, it takes some time to re parse the file and show its data. I want an activity indicator in the middle of the view when I click refresh button. And when parsing is done, that indicator should hide.

I am using this code but it is not working:

- (IBAction)refreshFeed:(id)sender
{
   UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
   [self.view addSubview:spinner];

   [spinner startAnimating];

   // parsing code code
    
   [spinner release];
}

Answer

Walter picture Walter · Feb 24, 2011

A UIActivityIndicator generally needs to be placed into a separate thread from the long process (parsing feed) in order to appear.

If you want to keep everything in the same thread, then you need to give the indicator time to appear. This Stackoverflow question addresses placing a delay in the code.

EDIT: Two years later, I think that any time you are using a delay to make something happen you are probably doing it wrong. Here is how I would do this task now:

- (IBAction)refreshFeed:(id)sender {
    //main thread
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; [self.view addSubview:spinner];

    //switch to background thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

        //back to the main thread for the UI call
        dispatch_async(dispatch_get_main_queue(), ^{
            [spinner startAnimating];
        });
        // more on the background thread

        // parsing code code

        //back to the main thread for the UI call
        dispatch_async(dispatch_get_main_queue(), ^{
            [spinner stopAnimating];
        });
    });
}