IOS / Objective-C:检查互联网连接的最快方法 - 2017年

时间:2017-02-28 14:41:23

标签: ios reachability internet-connection

我昨天在飞机上发现的用于检查互联网连接的代码非常缓慢。我在许多较早的SO answers检查NSUURL时使用该技术,但是,当在没有连接的飞机上使得应用程序基本上无法使用时,它确实需要十五秒或更长时间才能返回FALSE。

是否有可靠的异步方法可以做到这一点?人们在旧答案中推荐Tony Million的可达性等级,但它看起来非常复杂,Apple显然拒绝某些应用程序using it。如果有人能在2017年建议以最快,最可靠的方式检查互联网连接,我将不胜感激。谢谢。

- (BOOL)connected
    {
        NSURL *scriptUrl = [NSURL URLWithString:@"https://www.google.com"];
        NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
        if (data) {
            NSLog(@"Device is connected to the internet");
            return TRUE;
        }
        else {
            NSLog(@"Device is not connected to the internet");
            return FALSE;
        }
    }

1 个答案:

答案 0 :(得分:2)

即使在2017年,可达性也是正确的方式。

所有各种Reachability类都基于Apple的示例代码。

它可能看起来很复杂,因为它使用C API。但用法很简单:

- (BOOL)connected
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];

    if ([reach isReachable]) {
        NSLog(@"Device is connected to the internet");
        return TRUE;
    }
    else {
        NSLog(@"Device is not connected to the internet");
        return FALSE;
    }
}

如果您将使用Apple的Reachability类而不是Tony Million,请将[reach isReachable]替换为[reach currentReachabilityStatus] != NotReachable

不要担心Apple会拒绝使用它的应用程序。如果您遇到这种情况,只需将该类从Reachability重命名为MyReachability。