Piscean Piscean - 4 months ago 14
Objective-C Question

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

I am working with an app which parses an feed online. when i click 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 its not working.

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

[spinner startAnimating];

// parsing code code

[spinner release];
}

Answer

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];
        });
    });
}