【问题标题】:How to define a reachability timeout on ios如何在 ios 上定义可达性超时
【发布时间】:2012-04-11 11:47:25
【问题描述】:

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

我的代码:

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

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

【问题讨论】:

  • wifi 可用但不能上网?什么意思??
  • 表示路由器和iPad的wifi连接正常,但是没有网络连接。

标签: objective-c ios reachability


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,但我找到了一种指定超时的方法。我在 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多