在Swift中使用Apple的可达性类

我正在重写我现有的Objective-C代码(iOS)到Swift ,现在我正面临着Apple的Reachability类检查networking可用性的一些问题…在我现有的代码中,我正在使用以下内容来实现这一点。

 var reachability: Reachability = Reachability.reachabilityForInternetConnection() var internetStatus:NetworkStatus = reachability.currentReachabilityStatus() if (internetStatus != NotReachable) { //my web-dependent code } else { //There-is-no-connection warning } 

我得到这个错误: network status is not convertible to string在这一行:

 if (internetStatus != NotReachable) 

有没有获得networking状态的方法或类?

我需要这三个条件:

 NotReachable: Obviously, there's no Internet connection ReachableViaWiFi: Wi-Fi connection ReachableViaWWAN: 3G or 4G connection 

对于networking可用性(在Swift 2中工作):

 class func hasConnectivity() -> Bool { let reachability: Reachability = Reachability.reachabilityForInternetConnection() let networkStatus: Int = reachability.currentReachabilityStatus().rawValue return networkStatus != 0 } 

对于Wi-Fi连接:

 (reachability.currentReachabilityStatus().value == ReachableViaWiFi.value) 

尝试下面的代码

  let connected: Bool = Reachability.reachabilityForInternetConnection().isReachable() if connected == true { println("Internet connection OK") } else { println("Internet connection FAILED") var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK") alert.show() } 

把这段代码放到你的appDelegate中来检查可达性。

 //MARK: reachability class func checkNetworkStatus() -> Bool { let reachability: Reachability = Reachability.reachabilityForInternetConnection() let networkStatus = reachability.currentReachabilityStatus().rawValue; var isAvailable = false; switch networkStatus { case (NotReachable.rawValue): isAvailable = false; break; case (ReachableViaWiFi.rawValue): isAvailable = true; break; case (ReachableViaWWAN.rawValue): isAvailable = true; break; default: isAvailable = false; break; } return isAvailable; } 

简单地使用像这样

 do { let reachability: Reachability = try Reachability.reachabilityForInternetConnection() switch reachability.currentReachabilityStatus{ case .ReachableViaWiFi: print("Connected With wifi") case .ReachableViaWWAN: print("Connected With Cellular network(3G/4G)") case .NotReachable: print("Not Connected") } } catch let error as NSError{ print(error.debugDescription) }