Search code examples
iosios5uiactivityindicatorviewviewdidload

UIActivityIndicatorView not shown while doing work


I have made changes to the database in the next version of my app.

From the the end of the main view controller's viewDidLoad, I call a method that checks to see if the database is up to date. If it isn't a UIActivityIndicatorView is displayed while the database is repaired (takes 5-10 seconds).

That part goes like this:

[self.view addSubview: activityView];

//repair database
...
//done

[activityView removeFromSuperview];

I want the app to load, the UIActivityIndicatorView to display, fix the database, close the UIActivityIndicatorView.

The problem is that this all happens during the loading screen (default.png).

I added some logging to see when the activityView is called, when the database is being updated, etc., and can confirm that all of this is logged during the loading screen.

What should I do to solve this problem?


Solution

  • The problem is you're trying to do all this work on the main thread. The UI doesn't actually update until control returns to the runloop. Instead you need to display the activity indicator, then schedule your database work to be done on a background thread. Make sure UI input is disabled during this time. Once the work is complete, then you can call back to the main thread, remove the activity indicator, and enable UI interaction.

    Note that if you do this, you need to make sure your database work is done in a manner that's safe to occur on a background thread (e.g. if you're using CoreData, your background thread needs its own context, etc.)

    Also note that if you decide not to do this and instead just live with the default.png displaying, your app will actually end up being terminated if it takes longer than 5-10 seconds to do this work, and the user will never be able to successfully launch it.