苹果工程师建议完全依赖Rechability。
从SO post(块引用来源)
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.
我做了什么?
每当我需要例如
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
}
什么是正在发生的事情有一个连接,可达性将只如果连接失败测试。我制作了一个通用的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);
}
它不会崩溃您的应用程序,当你正在处理“零”数据参数自己,最后你确定原因。
希望这有助于!
UPDATE:
苹果可能会拒绝你的应用程序,如果你显示有关Internet连接一个假消息。他们对iPhone的声誉非常认真。如果互联网连接可用,但如果您的应用报告互联网连接不可用,它将被认为是非常严重的
当我们在主线程上调用Reachability时,我们发现代码中有很多超时崩溃。这会在某些不良网络条件下发生。因此,现在我们只在后台线程中调用它,并且仅将其用于“网络已发布”通知,而不是“可用于网络”测试。 – EricS
您不应_call_可达性。您将其设置并收听其通知。 –