Chen Harel
Chen Harel

Reputation: 10052

How to control Network Activity Indicator on iPhone

I know that in order to show/hide the throbber on the status bar I can use

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

But my program sends comm requests from many threads, and I need a location to control whether the throbber should be shown or hidden.

I thought about a centralized class where every comm request will register and this class will know if one-or-many requests are currently transferring bytes, and will turn the throbber on, otherwise - off.

Is this the way to go? why haven't Apple made the throbber appear automatically when networking is happening

Upvotes: 4

Views: 3042

Answers (2)

Skie
Skie

Reputation: 2012

Try to use something like this:

static NSInteger __LoadingObjectsCount = 0;

@interface NSObject(LoadingObjects)

+ (void)startLoad;
+ (void)stopLoad;
+ (void)updateLoadCountWithDelta:(NSInteger)countDelta;

@end

@implementation NSObject(LoadingObjects)

+ (void)startLoad {
    [self updateLoadCountWithDelta:1];
}

+ (void)stopLoad {
    [self updateLoadCountWithDelta:-1];
}

+ (void)updateLoadCountWithDelta:(NSInteger)countDelta {
    @synchronized(self) {
        __LoadingObjectsCount += countDelta;
        __LoadingObjectsCount = (__LoadingObjectsCount < 0) ? 0 : __LoadingObjectsCount ;

        [UIApplication sharedApplication].networkActivityIndicatorVisible = __LoadingObjectsCount > 0;
    }
}

UPDATE: Made it thread safe

Upvotes: 7

Robert Karl
Robert Karl

Reputation: 7816

Having some logic in your UIApplication subclass singleton seems like the natural way to handle this.

//@property bool networkThingerShouldBeThrobbingOrWhatever;
// other necessary properties, like timers
- (void)someNetworkActivityHappened {
    // set a timer or something
}
- (void)networkHasBeenQuietForABit
    // turn off the indicator.
    // UIApplcation.sharedApplication.networkActivityIndicatorVisible = NO;
}

Upvotes: 0

Related Questions