Blog

Avoid the clobber: Nest your network activity indicator updates

On the iPhone, when you are doing anything that uses the network, you’re supposed to let the user know something’s going on, via -[UIApplication setNetworkActivityIndicatorVisible:]. This takes a boolean.

That’s all well and good, but if you have more than one object in your app that may do things with the network simultaneously, you’re going to clobber yourself.

A nice and easy solution: Maintain an activity counter and create a category on UIApplication to maintain it, and show or hide the indicator as appropriate. Then, whenever you start doing something with the network:

[[UIApplication sharedApplication] showNetworkActivityIndicator];

…And when you’re done:

[[UIApplication sharedApplication] hideNetworkActivityIndicator];

Here’s a category that’ll do it:

@interface UIApplication (TPAdditions)
- (void)showNetworkActivityIndicator;
- (void)hideNetworkActivityIndicator;
@end
 
 
static NSInteger __activityCount = 0;
 
@implementation UIApplication (TPAdditions)
- (void)showNetworkActivityIndicator {
    if ( __activityCount == 0 ) {
        [self setNetworkActivityIndicatorVisible:YES];
    }
    __activityCount++;
}
- (void)hideNetworkActivityIndicator {
    __activityCount--;
    if ( __activityCount == 0 ) {
        [self setNetworkActivityIndicatorVisible:NO];
    }    
}
@end
, , , . Bookmark the permalink. Both comments and trackbacks are currently closed.