如何在顶部状态栏显示加载指示器

我注意到,Safari和Mail等应用在访问networking时,会在状态栏(电话顶部的栏)中显示一个加载指示符。 有没有办法在SDK应用程序中做同样的事情呢,还是只有苹果?

它在UIApplication中:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

为迅速:

 UIApplication.shared.isNetworkActivityIndicatorVisible = true 

我发现下面的macros很有用!

 #define ShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES #define HideNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = NO 

所以你可以调用ShowNetworkActivityIndicator();HideNetworkActivityIndicator(); 从你的应用程序(只要标题是包括当然!)。

我写了一个单例解决多个连接的问题,通过保持一个正在发生的事情的计数器(避免在连接返回时移除状态,但是另一个仍然处于活动状态):

头文件:

 #import <Foundation/Foundation.h> @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; 

一旦networking通话完成,您还需要注意隐藏活动指示器。

如果你使用AFNetworking ,那么你不需要做太多的事情。

AppDelegate类中进行以下更改:

  1. 导入AFNetworking/AFNetworkActivityIndicatorManager.h

  2. 把这个放在didFinishLaunchingWithOptions:

[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]

确保您在主线程上运行它也可能是有帮助的,因为它与UI相关。

 dispatch_async(dispatch_get_main_queue(), ^{ [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; });