6

我使用 Reachability 类来了解我是否有可用的 Internet 连接。问题是当 wifi 可用但没有互联网时,该- (NetworkStatus) currentReachabilityStatus方法需要太多时间。

我的代码:

Reachability* reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

应用程序暂时“冻结”在第二行。如何定义此等待的最长时间?

4

2 回答 2

3

我不这么认为。但更重要的是,如果可以的话,我认为你不会想要(你可能会得到误报)。让可达性顺其自然。

如果您查看 Reachability 演示项目,那么这个概念并不是在您需要 Internet 时调用reachabilityWithHostName和检查。currentReachabilityStatus您在应用程序委托的 didFinishLaunchingWithOptions 期间调用 currentReachabilityStatus,设置通知,当 Internet 连接发生变化时,Reachability 会告诉您。我发现currentReachabilityStatus当我(a)在启动时设置可达性时,后续检查非常快(无论连接性如何);但是 (b) 以即时方式检查连通性。

如果您绝对需要立即开始处理,那么问题是您是否可以将其推入后台(例如dispatch_async())。例如,我的应用程序从服务器检索更新,但因为这是在后台发生的,所以我和我的用户都不知道有任何延迟。

于 2012-04-11T15:31:30.567 回答
0

I was having issues with the same thing but I found a way to specify a timeout. I replaced this method inside the Reachability Class from Apple.

- (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;
}
于 2015-01-14T18:57:27.073 回答