开发者

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


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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜