Search code examples
iphoneuiactivityindicatorviewviewdidloadviewdidappear

Trouble with Displaying an Activity Indicator while Data Loads


I feel as though there is a really simple solution to my problem, but thus far I have had little success... I want to load my initial .xib file (exiting the default.png splash screen early), so that I may display an activity indicator while loading my html data and setting the text label fields created by my xib file.

Unfortunately, when I execute the following code below, I display my default.png image until all of the data is loaded from each website... What may I change in order to first display my mainView, then start the activity indicator, load my html data, and set the text labels in my mainView?

@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];

[activityIndicator startAnimating];

[self runTimer];

}

- (void)viewDidAppearBOOL)animated {

[super viewDidAppear:animated];

[self loadHTMLData1];

[self loadHTMLData2];

[self loadHTMLData3];

[self loadHTMLData4];

[activityIndicator stopAnimating];

}
...

Solution

  • It's all to do with how iOS updates the ui. When you call

    [activityIndicator startAnimating];
    

    it doesn't mean start animating immediately, it means you're telling the ui the next time you are updating the display, start animating.

    All of this updating happens on the main thread (if you haven't made a thread, you're already on the main thread) so if you do something else that takes a long time, it will do this before updating the display.

    There are a few ways to fix this and they all involve making another thread that runs in the background.

    Take a look at NSOperation (and NSOperationQueue) - this will let you queue up individual tasks that iOS will run in the background for you. then when they are complete you can update your display again and turn off your activity indicator.

    There's NSOperationQueue tutorials all over google :)

    Hope that helps.