我想检查一下我是否可以在iOS上使用Cocoa Touch库或在macOS上使用Cocoa库连接互联网。

我想出了一个方法来做这个使用NSURL。我的方法似乎有点不可靠(因为即使谷歌也可能有一天宕机,依赖第三方似乎很糟糕),虽然如果谷歌没有响应,我可以检查其他一些网站的响应,但这似乎是浪费和不必要的应用程序开销。

- (BOOL)connectedToInternet {
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}

是我做得不好,(更不用说stringWithContentsOfURL已弃用在iOS 3.0和macOS 10.4),如果是这样,有什么更好的方法来实现这一点?


当前回答

从https://github.com/tonymillion/Reachability获取Reachabilty类,在你的项目中添加系统配置框架,在你的类中导入Reachability.h,并实现如下所示的自定义方法:

- (BOOL)isConnectedToInternet
{
    //return NO; // Force for offline testing
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    return !(netStatus == NotReachable);
}

其他回答

我认为这是最好的答案。

“是”意味着有联系。“No”表示断开连接。

#import "Reachability.h"

 - (BOOL)canAccessInternet
{
    Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStats = [IsReachable currentReachabilityStatus];

    if (internetStats == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

步骤1:在项目中添加Reachability类。 步骤2:导入Reachability类 步骤3:创建下面的函数 - (BOOL)checkNetConnection { self.internetReachability =[可达性reachabilityForInternetConnection]; [self.internetReachability startNotifier]; NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus]; switch (netStatus) { 案例NotReachable: { 返回NO; } 案例ReachableViaWWAN: { 返回YES; } 案例ReachableViaWiFi: { 返回YES; } } } 步骤4:调用函数如下所示: 如果(![self checkNetConnection]) { [GlobalFunctions showAlert: @”“ 信息:@“请连接到互联网!” canBtntitle:零 otherBtnTitle: @“Ok”); 返回; } 其他的 { 日志。V(“internet is connected”,“ok”); }

这里有一个漂亮的,使用ARC和gcd的现代化可达性:

可达性

只有Reachability类已经更新。你现在可以使用:

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

if (remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
else if (remoteHostStatus == ReachableViaWWAN) { NSLog(@"reachable via wwan");}
else if (remoteHostStatus == ReachableViaWiFi) { NSLog(@"reachable via wifi");}

我发现使用SimplePingHelper库很简单。

示例代码:chrishulbert/SimplePingHelper (GitHub)