如何在iPhone上控制网络活动指示器

4

我知道为了在状态栏中显示/隐藏 throbber,我可以使用以下代码:

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

但是我的程序会从多个线程发送通信请求,我需要一个位置来控制是否显示或隐藏throbber。

我考虑过一个集中的类,在这个类中每个通信请求都会注册,这个类将知道当前是否有一个或多个请求正在传输字节,并打开或关闭throbber。

这是正确的做法吗?为什么苹果没有在网络传输时自动显示throbber呢?

2个回答

7
尝试使用类似以下的内容:

尝试使用以下内容:

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

更新:使其线程安全


1
虽然这是一个老问题,但仍然需要注意:这个解决方案不是线程安全的,竞争条件可能会导致即使没有真正执行任何网络活动(或反之亦然),指示器也会被显示出来。 - FurloSK

0

在你的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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接