我使用可达性类来了解我是否有可用的互联网连接。问题是当wifi可用但互联网不可用时,- (NetworkStatus) currentReachabilityStatus
方法需要太多时间。
我的代码:
Reachability* reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
应用程序暂时"冻结"在第二行。如何定义此等待的最长时间?
我不这么认为。但更重要的是,如果可以的话,我认为你不会想要(你可能会得到误报)。让可达性顺其自然。
如果您查看可访问性演示项目,其概念不是在需要 Internet 时调用reachabilityWithHostName
并检查currentReachabilityStatus
。您可以在应用程序委托的 didFinishLaunchingWithOptions 期间调用 currentReachabilityStatus,设置通知,Reachability 会在互联网连接发生更改时通知您。我发现当我 (a) 在启动时设置可达性时,对currentReachabilityStatus
的后续检查非常快(无论连接性如何);但 (b) 及时检查连接性。
如果您绝对需要立即开始处理,那么问题是您是否可以将其推送到后台(例如 dispatch_async()
)。例如,我的应用程序从服务器检索更新,但由于这是在后台发生的,我和我的用户都不知道有任何延迟。
我在同一件事上遇到了问题,但我找到了一种指定超时的方法。我在Apple的Reachability Class中替换了此方法。
- (NetworkStatus)currentReachabilityStatus
{
NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL SCNetworkReachabilityRef");
//NetworkStatus returnValue = NotReachable;
__block SCNetworkReachabilityFlags flags;
__block BOOL timeOut = NO;
double delayInSeconds = 5.0;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(delay, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){
timeOut = YES;
});
__block NetworkStatus returnValue = NotReachable;
__block BOOL returned = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags))
{
if (_alwaysReturnLocalWiFiStatus)
{
returnValue = [self localWiFiStatusForFlags:flags];
}
else
{
returnValue = [self networkStatusForFlags:flags];
}
}
returned = YES;
});
while (!returned && !timeOut) {
if (!timeOut && !returned){
[NSThread sleepForTimeInterval:.02];
} else {
break;
}
}
return returnValue;
}