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


当前回答

对于我的iOS项目,我建议使用

可达性类

Swift声明。对我来说,它工作得很好

Wi-Fi和蜂窝数据

import SystemConfiguration

public class Reachability {

    class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }

        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        let ret = (isReachable && !needsConnection)
        return ret
    }
}

使用条件语句,

if Reachability.isConnectedToNetwork() {
    // Enter your code here
}
}
else {
    print("NO Internet connection")
}

这个类在几乎所有应用程序使用Internet连接的情况下都很有用。 例如,如果条件为真,就可以调用API或执行任务。

其他回答

创建一个AFNetworkReachabilityManager对象,并使用以下代码跟踪网络连通性

self.reachabilityManager = [AFNetworkReachabilityManager managerForDomain:@"yourDomain"];
[self.reachabilityManager startMonitoring];
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                break;
            case AFNetworkReachabilityStatusNotReachable:
                break;
            default:
                break;
        }
    }];

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

步骤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");
    }
}

Swift 3 / Swift 4

您必须首先导入

import SystemConfiguration

您可以通过以下方法检查Internet连接。

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}

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

当使用iOS 12或macOS v10.14 (Mojave)或更新版本时,您可以使用NWPathMonitor而不是史前可达性类。作为奖励,你可以很容易地检测到当前的网络连接类型:

import Network // Put this on top of your class

let monitor = NWPathMonitor()

monitor.pathUpdateHandler = { path in
    if path.status != .satisfied {
        // Not connected
    }
    else if path.usesInterfaceType(.cellular) {
        // Cellular 3/4/5g connection
    }
    else if path.usesInterfaceType(.wifi) {
        // Wi-Fi connection
    }
    else if path.usesInterfaceType(.wiredEthernet) {
        // Ethernet connection
    }
}

monitor.start(queue: DispatchQueue.global(qos: .background))

更多信息请访问:https://developer.apple.com/documentation/network/nwpathmonitor