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


当前回答

迅捷5号,我是阿拉莫火,主持人

// Session reference
var alamofireSessionManager: Session!

func checkHostReachable(completionHandler: @escaping (_ isReachable:Bool) -> Void) {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 1
    configuration.timeoutIntervalForResource = 1
    configuration.requestCachePolicy = .reloadIgnoringLocalCacheData

    alamofireSessionManager = Session(configuration: configuration)

    alamofireSessionManager.request("https://google.com").response { response in
        completionHandler(response.response?.statusCode == 200)
    }
}

// Using
checkHostReachable() { (isReachable) in
    print("isReachable:\(isReachable)")
}

其他回答

检查Internet连接的可用性(iOS) Xcode 8, Swift 3.0

这是一个简单的方法来检查网络可用性,如我们的设备是否连接到任何网络。我已经成功地将其翻译为Swift 3.0,这里是最终的代码。现有的Apple Reachability类和其他第三方库似乎太复杂了,无法翻译到Swift中。 这适用于3G、4G和WiFi连接。 不要忘记在你的项目构建器中添加“SystemConfiguration.framework”。

//Create new swift class file Reachability in your project.
import SystemConfiguration
public class InternetReachability {

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(sizeofValue(zeroAddress))
   zeroAddress.sin_family = sa_family_t(AF_INET)
   let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
          SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
   }
   var flags: SCNetworkReachabilityFlags = 0
   if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
          return false
   }
   let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
   let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

   return isReachable && !needsConnection
  }
}

// Check network connectivity from anywhere in project by using this code.
 if InternetReachability.isConnectedToNetwork() == true {
         print("Internet connection OK")
  } else {
         print("Internet connection FAILED")
  }

苹果提供了一个示例应用程序,它正是这样做的:

可达性

迅捷5号,我是阿拉莫火,主持人

// Session reference
var alamofireSessionManager: Session!

func checkHostReachable(completionHandler: @escaping (_ isReachable:Bool) -> Void) {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 1
    configuration.timeoutIntervalForResource = 1
    configuration.requestCachePolicy = .reloadIgnoringLocalCacheData

    alamofireSessionManager = Session(configuration: configuration)

    alamofireSessionManager.request("https://google.com").response { response in
        completionHandler(response.response?.statusCode == 200)
    }
}

// Using
checkHostReachable() { (isReachable) in
    print("isReachable:\(isReachable)")
}
Pod `Alamofire` has `NetworkReachabilityManager`, you just have to create one function 

func isConnectedToInternet() ->Bool {
        return NetworkReachabilityManager()!.isReachable
}

只有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");}