iOS:可达性 – 返回到应用程序后,startNotifier失败
我有Reachability完全按照在这个线程中的build议工作。
我正在使用开源可达性 。 不过,我不使用块,但通知,因此该过程是非常类似于苹果的可达性代码。
我第一次启动应用程序,我运行这个,它很好。
Reachability *reachability = [reach hostReachability]; [reachability startNotifier];
reachabilityChanged:事件正在触发:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachability_Changed:) name:kReachabilityChangedNotification object:nil];
但是,一旦我按回家button,回到应用程序, startNotifier
内部返回一个NO而不是一个YES。
// Set it as our reachability queue, which will retain the queue if(!SCNetworkReachabilitySetDispatchQueue(self.reachabilityRef, self.reachabilitySerialQueue)) { #ifdef DEBUG NSLog(@"SCNetworkReachabilitySetDispatchQueue() failed: %s", SCErrorString(SCError())); #endif ... return NO;
因此上述事件再也不会被解雇。
除非我使用这个错误,并且startNotifier
应该只在init
被调用一次,当可达性被实例化,永远不会再次?
self.hostReachability = [Reachability reachabilityWithHostname:_HOST];
您只需要在init / load上调用[self.hostReachability startNotifier]
一次。 下面是您的基本需求的简要介绍,使用通知而不是链接的线程上的块方法:
-
将tonymillion / Reachability库添加到您的项目。
-
为您的Reachability对象创build属性,以确保它保留,例如。
@interface ViewController () { NSString *_HOST; } @property Reachability *hostReachability; @end
-
注册更改通知,并启动通知程序,例如。
- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; _HOST = @"www.google.com"; self.hostReachability = [Reachability reachabilityWithHostname:_HOST]; [self.hostReachability startNotifier]; } - (void)viewDidUnload { [super viewDidUnload]; [[NSNotificationCenter defaultCenter] removeObserver:self]; }
-
最后,创build一个
reachabilityChanged:
方法来处理您对可达性更改的响应,例如。- (void)reachabilityChanged:(NSNotification*)notification { Reachability *notifier = [notification object]; NSLog(@"%@", [notifier currentReachabilityString]); }
注意:如果按主页button并卸载应用程序,则Reachability中的更改应在返回到应用程序后立即触发通知。