我注意到一些应用程序(如Safari和Mail)在访问网络时在状态栏(手机最顶部的栏)中显示加载指示符.有没有办法在SDK应用程序中做同样的事情,或者这只是Apple的事情?
它在UIApplication中:
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
对于swift:
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
我发现以下宏非常有用!
#define ShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES #define HideNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = NO
所以你可以在你的应用程序中调用ShowNetworkActivityIndicator();
或调用HideNetworkActivityIndicator();
(只要包含标题!).
我写了一个单例,通过保持对正在发生的事情的计数器来解决多个连接的问题(以避免在连接返回但另一个仍处于活动状态时删除状态):
头文件:
#import@interface RMActivityIndicator : NSObject -(void)increaseActivity; -(void)decreaseActivity; -(void)noActivity; +(RMActivityIndicator *)sharedManager; @end
和实施:
#import "RMActivityIndicator.h" @interface RMActivityIndicator () @property(nonatomic,assign) unsigned int activityCounter; @end @implementation RMActivityIndicator - (id)init { self = [super init]; if (self) { self.activityCounter = 0; } return self; } -(void)increaseActivity{ @synchronized(self) { self.activityCounter++; } [self updateActivity]; } -(void)decreaseActivity{ @synchronized(self) { if (self.activityCounter>0) self.activityCounter--; } [self updateActivity]; } -(void)noActivity{ self.activityCounter = 0; [self updateActivity]; } -(void)updateActivity{ UIApplication* app = [UIApplication sharedApplication]; app.networkActivityIndicatorVisible = (self.activityCounter>0); } #pragma mark - #pragma mark Singleton instance +(RMActivityIndicator *)sharedManager { static dispatch_once_t pred; static RMActivityIndicator *shared = nil; dispatch_once(&pred, ^{ shared = [[RMActivityIndicator alloc] init]; }); return shared; } @end
例:
[[RMActivityIndicator sharedManager]increaseActivity]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:self.networkReceiveProcessQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { [[RMActivityIndicator sharedManager]decreaseActivity]; }
一行代码:
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
完成网络呼叫后,您还需要注意隐藏活动指示器.
如果你使用AFNetworking
,那么你不需要做太多.
在AppDelegate
课程中进行以下更改:
进口 AFNetworking/AFNetworkActivityIndicatorManager.h
把它放进去 didFinishLaunchingWithOptions:
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]