我想检查一下我是否可以在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),如果是这样,有什么更好的方法来实现这一点?


当前回答

关于Reachability的iOS 5版本是darkseed/Reachability.h。不是我的!=)

其他回答

请尝尝这个。它会帮助你的(斯威夫特)

通过CocoaPods或Carthage: Reachability安装 导入可达性并在Network类中使用它 进口可达性 网络{ private let internetReachability:可达性? var isReachable: Bool = false init () { self.internetReachability = Reachability.init() {做 试试self.internetReachability ? .startNotifier () addobserver (self, selector: #selector(self. handlenetworkchange),名称:.reachabilityChanged,对象:internetReachability) } catch { 打印("无法启动可达性通知程序") } } @objc private func handleNetworkChange(通知:通知){ Let可达性=通知。对象!可达性 如果可达性。连接!= .none { 自我。isReachable = true } 其他{ 自我。isReachable = false } print("Internet Connected: \(self.isReachable)") //打印网络连接状态 } } 在你需要的地方使用下面的方法。 var networkOBJ = Network() //使用"networkOBJ. "“网络状态可达” 打印(networkOBJ.isReachable)

很简单的…试试下面这些步骤:

步骤1:将SystemConfiguration框架添加到项目中。


步骤2:将以下代码导入到头文件中。

#import <SystemConfiguration/SystemConfiguration.h>

第三步:使用以下方法

类型1: - (BOOL) currentNetworkStatus { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; BOOL连接; BOOL与; Const char *host = "www.apple.com"; SCNetworkReachabilityRef reachabilityreachabilitycreatewithname (NULL, host); SCNetworkReachabilityFlags旗帜; connected = SCNetworkReachabilityGetFlags(可达性,&flags); isConnected = NO; isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired); CFRelease(可达性); 返回与; }


类型2: 导入头文件:# Import "Reachability.h" (保龄球)currentNetworkStatus { 可达性*可达性=[互联网连接的可达性]; NetworkStatus NetworkStatus =[可达性currentReachabilityStatus]; 返回networkStatus !=不可访问; }


第四步:使用方法:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}

使用Apple的Reachability代码,我创建了一个函数,可以正确地检查这一点,而无需包含任何类。

在你的项目中包含SystemConfiguration.framework。

进行一些导入:

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

现在只需调用这个函数:

/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability
 */
+(BOOL)hasConnectivity {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    if (reachability != NULL) {
        //NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
            {
                // If target host is not reachable
                return NO;
            }

            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
            {
                // If target host is reachable and no connection is required
                //  then we'll assume (for now) that your on Wi-Fi
                return YES;
            }


            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
            {
                // ... and the connection is on-demand (or on-traffic) if the
                //     calling application is using the CFSocketStream or higher APIs.

                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                {
                    // ... and no [user] intervention is needed
                    return YES;
                }
            }

            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
            {
                // ... but WWAN connections are OK if the calling application
                //     is using the CFNetwork (CFSocketStream?) APIs.
                return YES;
            }
        }
    }

    return NO;
}

这是为你测试的iOS 5。

从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);
}

进口“Reachability.h”

-(BOOL)netStat
{
    Reachability *test = [Reachability reachabilityForInternetConnection];
    return [test isReachable];
}