简体   繁体   English

可达性和通知中心

[英]Reachability and notificationcenter

I need my app to constantly listen for reachability changes and update my views according to the network status , i am thinking about using the notificationcenter , and let all my views listen for changes, but i have no idea how to implement this. 我需要我的应用程序不断监听可访问reachability更改并根据network status更新我的视图,我正在考虑使用notificationcenter ,让我的所有视图都听取更改,但我不知道如何实现它。

I know how to use the notificationcenter and Reachability but i can't seem to find a place to implement the Reachability check . 我知道如何使用notificationcenterReachability但我似乎无法找到实现Reachability check的地方。

Where should i check for network changes, and notify the other ViewControllers ? 我应该在哪里检查网络更改,并通知其他ViewControllers

I don't think AppDelegate is the right place, and if i put the Reachability check in a ViewController the network checking is only being performed as long as the ViewController is "active". 我不认为AppDelegate是正确的地方,如果我将Reachability检查放在ViewController中,只要ViewController处于“活动状态”,就会执行网络检查。

Create a "singleton" Reachability and initialize it at app launch. 创建“单身” Reachability并在应用启动时初始化它。

Let the singleton check for reachability periodically, eg with NSTimer . 让单例定期检查可达性,例如使用NSTimer It can then notify any other active views that registered with NSNotificationCenter . 然后,它可以通知在NSNotificationCenter中注册的任何其他活动视图。

// AppDelegate.m: 

@property (nonatomic, strong) Reachability *reachability;

// in applicationDidFinishLaunching...
self.reachability = [[Reachability alloc] init]; 

and

// Reachability.m

-(id)init {
   self = [super init];
   if (self) {
     [self setupTheTimer];
   }
   return self;
}

I would create a singleton NSObject class that handles all the network checks. 我将创建一个处理所有网络检查的单例NSObject类。

Name it like NetworkChecker. 将其命名为NetworkChecker。

Create a delegate for the callback, like NetworkCheckerDelegate with a method like: 使用如下方法创建回调委托,如NetworkCheckerDelegate

@protocol NetworkCheckerDelegate <NSObject>

-(void)networkStatusUpdated:(NSInteger)networkStatus;

@end

@interface NetworkChecker : NSObject
{
    id<NetworkCheckerDelegate> networkDelegate;
}

Add a method to start the network checking and add a delegate to it like: 添加一个方法来启动网络检查并向其添加委托,如:

+(void)updateNetworkWithDelegate:(id<NetworkCheckerDelegate>)delegate
{
    networkDelegate = delegate;

    //Set timer to do Reachability checks
}

-(void)timerIsCompleted
{
    //Do Reachability check

    if( newNetworkState != oldNetworkState ){
        [networkDelegate networkStatusUpdated:newNetworkState];
    }
}

Then in each ViewController you need it you can do (do this in viewDidLoad): 然后在每个ViewController你需要它可以做(在viewDidLoad中执行此操作):

[NetworkChecker updateNetworkWithDelegate:self];

And implement the following to do something after the network status changed: 并在网络状态发生变化后执行以下操作:

-(void)networkStatusUpdated:(NSInteger)networkStatus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM