如何控制网络活动指示灯iPhone
问题描述:
我知道的是,为了显示/隐藏状态栏上的活动指示器我可以使用如何控制网络活动指示灯iPhone
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
但是我的程序从多个线程发出通讯请求,我需要一个位置,以控制活动指示器是否应显示或隐藏。
我想到了一个集中的类,每一个通讯请求将注册这个类就会知道,如果一个或一对多的请求当前传输字节,将打开活动指示器,否则 - 关闭。
这是要走的路?为什么没有苹果使网络出现时自动出现的跳动
答
尝试使用这样的:
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:制造线程安全
答
在你的UIApplication
子类中有一些逻辑单例似乎是处理这种情况的自然方法。
//@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;
}
老问题,但还是:这个解决方案不是线程安全的,竞争条件可能导致要显示指示器即使确实不执行网络活动(或反之亦然)。 – FurloSK 2012-10-03 09:31:43
我已经更新代码,使其线程安全 – Skie 2012-10-05 09:28:27