Updated: Easy Way to Get a UIActivityIndicatorView to startAnimating Before Starting an NSURLConnection sendSynchronousRequest
Posted by Tres Sun, 24 May 2009 04:17:00 GMT
<edit> I can’t really recommend using this method because it locks up the UI for the entire time it runs. If you’re interested in allowing your user to still have access to controls during the time it takes to load, I’d recommend taking a look at NSThread detachNewThreadSelector: toTarget: withObject:. Not only will it make for happier users, but another thread means that UIActivityIndicatorView works without any hacks.</edit>
The problem with running an NSURLConnection sendSynchronousRequest: is that the request runs in the same thread as the main run loop, so esentially for the duration of your request and the server’s response nothing happens that the user can see. No problem, right? Just light up an activity indicator and let your user know that magic things are happening. The only problem is that the activity indicator never shows up until about microsecond before it’s hidden again. Essentially it never appears.
This happens because the is the app never gets back to the UIKit runloop in between calls to the UIActivityIndicatorView.
Now you could send the request in another thread and be done with it. Thread programming is fun and everything, but if you don’t have to manage another thread, why? You can get let UIKit set up your interface before locking everything up by using NSTimer.
NSTimer *delayTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(myURLLoadingFunction) userInfo:nil repeats:NO];
Yeah, it’s a hack, but it works. And it doesn’t incur the hazards of using multiple threads.