Since NetworkActivityIndicatorVisible
can be set from several points while a connection is still active, you need to track the number of calls that enable/disable it. The following UIApplication
category does just that using a static variable:
// file UIApplication+NetworkActivity.h
@interface UIApplication (NetworkActivity)
- (void)showNetworkActivityIndicator;
- (void)hideNetworkActivityIndicator;
@end
// file UIApplication+NetworkActivity.m
#import "UIApplication+NetworkActivity.h"
static NSInteger activityCount = 0;
@implementation UIApplication (NetworkActivity)
- (void)showNetworkActivityIndicator {
if ([[UIApplication sharedApplication] isStatusBarHidden]) return;
@synchronized ([UIApplication sharedApplication]) {
if (activityCount == 0) {
[self setNetworkActivityIndicatorVisible:YES];
}
activityCount++;
}
}
- (void)hideNetworkActivityIndicator {
if ([[UIApplication sharedApplication] isStatusBarHidden]) return;
@synchronized ([UIApplication sharedApplication]) {
activityCount--;
if (activityCount <= 0) {
[self setNetworkActivityIndicatorVisible:NO];
activityCount=0;
}
}
}
@end
Now import UIApplication+NetworkActivity.h
in your client code and call
// on connection started:
[[UIApplication sharedApplication] showNetworkActivityIndicator];
// on connection finished:
[[UIApplication sharedApplication] hideNetworkActivityIndicator];
If your concern is that the indicator blinks for only a second, you don't need a background process. Just call [self performSelector:@selector(loadSources) withObject:Nil afterDelay:0.1]
so the UI thread has time to start the network indicator animation before you block the main thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…