ash*_*sky 5 iphone objective-c reachability nsnotificationcenter
我的iphone应用程序非常简单,一个视图处理所有内容,在viewDidLoad中我检查是否有互联网连接,如果我们从网络加载,如果不是,我们从本地资源加载.这很好用.
//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
}
}
Run Code Online (Sandbox Code Playgroud)
为了测试我的handleNetworkChange事件,我关掉了所有的蜂窝数据,但是打开了wifi.在无线网络的范围内我启动了应用程序,一切都很完美.然后我走出wifi的范围之外,但我的handleNetworkChange从未触发(使用uiAlertView测试).站在wifi的范围之外,我的应用程序启动离线消息就好了.
我怀疑这是ViewController生命周期的问题,这个代码应该放在AppDelegate函数中吗?可能这是一个更好的设计开始.
ash*_*sky 18
事实证明这是一个内存管理问题,因为我没有保留可达性变量,因此只要它超出范围,就会调用dealloc并调用stopNotifier方法.因此我没有更新,因为我会走出范围.
所以代替:
reachability = [Reachability reachabilityForInternetConnection];
Run Code Online (Sandbox Code Playgroud)
我做
reachability = [[Reachability reachabilityForInternetConnection] retain];
Run Code Online (Sandbox Code Playgroud)
一切正常!
通过所有这些我学到的一件很酷的事情就是你可以通过简单地关闭机场来模拟模拟器中丢失的连接.不再需要在外面闲逛.:)
| 归档时间: |
|
| 查看次数: |
8387 次 |
| 最近记录: |