可达性网络更改事件未触发 [英] Reachability network change event not firing

查看:141
本文介绍了可达性网络更改事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iphone应用非常简单,有一个处理所有内容的视图,在viewDidLoad中,我检查是否有互联网连接,如果我们从网络加载,如果不是,我们从本地资源加载。这很好。

My iphone app is pretty simple with one view that handles everything, in viewDidLoad I check to see if we have an internet connection and if we do we load from the web and if not we load from a local resource. And this works fine.

//in viewDidOnload    
[[NSNotificationCenter defaultCenter] addObserver:self 
                                          selector:@selector(handleNetworkChange:) 
                                          name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];

if (status == NotReachable) {
    //Do something offline
} else {
    //Do sometihng on line
}

- (void)handleNetworkChange:(NSNotification *)notice{
 NetworkStatus status = [reachability currentReachabilityStatus];
 if (status == NotReachable) {
  //Change to offline Message
 } else {
  //Relaunch online application
 }

}

为了测试我的handleNetworkChange事件,我关闭了所有蜂窝数据,但是打开了wifi。在wifi的范围内,我启动了应用程序,一切都很完美。然后我走出wifi的范围之外,但我的handleNetworkChange从未触发(使用uiAlertView测试)。站在wifi的范围之外我的应用程序启动离线消息就好了。

To test my handleNetworkChange event I turned off all cellular data but left the wifi on. Within range of the wifi I started the app and everything works perfect. Then I walk outside of the wifi's range, but my handleNetworkChange never fires (tested using an uiAlertView). Standing outside of the wifi's range my app launches the offline message just fine.

我怀疑这是ViewController生命周期的问题,这个代码应放在AppDelegate函数中吗?可能这是一个更好的设计开始。

My suspicion is that it is an issue with the ViewController's lifecycle, should this code be placed in the AppDelegate function? Possibly that's a better design to start with.

推荐答案

原来这是一个内存管理问题,因为我没有保留可达性变量,因此只要它超出范围,就会调用dealloc并调用stopNotifier方法。因此没有更新,因为我会走出范围。

Turns out it was a memory management issue, as I was not retaining the reachability variable, so as soon as it would go out of scope the dealloc would be called and that called the stopNotifier method. Hence no updates as I would walk out of range.

所以而不是:

reachability = [Reachability reachabilityForInternetConnection];

我做

reachability = [[Reachability reachabilityForInternetConnection] retain];

一切正常!

一个很酷我通过所有这些学到的东西是你可以通过简单地关闭机场来模拟模拟器中丢失的连接。不再需要在外面闲逛。 :)

One cool thing I learned through all of this is that you can simulate a lost connection in the simulator by simply turning Airport Off. No more having to wander around outside. :)

这篇关于可达性网络更改事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆