iOS可达性testing

对于我们的应用程序,只要应用程序用户试图发布消息,我们就使用以下代码来检查互联网连接。 当我们testing这个function时,在开启飞行模式时它可以正常工作。 然后,当我们closures飞行模式时,连接的呼叫仍然返回NO。 这可能是什么原因? 我们是否需要额外的“设置”的顺序才能得到它的权利? 如收听networking状态更改通知?

+ (BOOL)connected { Reachability *hostReach = [Reachability reachabilityForInternetConnection]; NetworkStatus netStatus = [hostReach currentReachabilityStatus]; return !(netStatus == NotReachable); } 

苹果工程师已经提出完全依赖Rechability。

从SOpost (blockquote的来源)

 On a WWDC talk this year the Apple engineer on stage recommended users to never base the application internet access on the Reachability example app status. Often reachability doesn't provide a complete information (it is based on a complex mechanism) and the suggestion provided by the engineer was this: 1. try to do your internet connection, whatever it is the Reachability status; then set your UI hint based on success/fail result 2. if it fails due to networking issue, then register to Reachability and retry again when Reachability gives the green light; this is needed when you want to recover automatically from the fail condition 3. in any case give the user the possibility to "force a retry", whatever is the Reachability status. If it succeeds, reset your UI hint immediately. 

我做了什么 ?

每次我都需要build立连接

 NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myadress.com"]]]; [self performSelectorOnMainThread:@selector(responseHandler:) withObject:data waitUntilDone:TRUE]; - (void)responseHandler:(NSData *)responseData { if(!responseData) { ReachabilityController *reachability = [[ReachabilityController alloc] init]; [reachability checkReachability]; return; } // you handle your data } 

发生什么事情,只有在连接失败的情况下才能testing可达性。 我做了一个通用的ReachabilityController只处理可达性。 我这样做,这样我每次发出请求都可以从其他所有控制器拨打电话。

我的ReachabilityController.m看起来像

 -(void) checkReachability { Reachability* internetAvailable = [Reachability reachabilityForInternetConnection]; NetworkStatus netStatus = [internetAvailable currentReachabilityStatus]; NSString *messageText; if (netStatus == NotReachable) { messageText = [NSString stringWithFormat:@"Internet access not available"]; } else { Reachability *netReach = [Reachability reachabilityWithHostName:host]; NetworkStatus hostStatus = [netReach currentReachabilityStatus]; if (hostStatus == NotReachable) { messageText = [NSString stringWithFormat:@"Host Unreachable"]; } else { messageText = [NSString stringWithFormat:@"Problem with remote service"]; } } NSLog(@"%@", messageText); } 

它不会崩溃你的应用程序,因为你自己处理“无”数据参数,最后你正在确定原因。

希望这可以帮助!

更新:

如果您显示有关Internet连接的错误消息,苹果可能会拒绝您的应用程序。 他们对iPhone的声誉非常认真。 如果互联网连接可用,但是如果您的应用程序报告互联网连接不可用, 则将被视为非常严重

你应该只是尝试networking连接,而不是使用可达性。 NSURLConnection将导致无线电启动。 尽pipe如此,一定要在出现错误时处理错误。

你正在使用某种便利的构造函数来检查可达性 – 这是行不通的。

在这里find如何使用可达性的最好的例子之一:

https://stackoverflow.com/a/3597085/653513

或者EricS所build议的,根本不使用可达性 – 这是一个可行的select。