在Swift中使用Apple的可达性类

时间:2014-09-19 07:43:00

标签: ios swift

我正在将我现有的Objective-C代码(iOS)重写为Swift,现在我正面临着用于检查网络可用性的Reachability类Apple的一些问题...在我现有的代码中,我是使用以下内容实现这一目标。

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)

是否有获取网络状态的方法或类?

我需要这三个条件:

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

4 个答案:

答案 0 :(得分:19)

对于网络可用性(适用于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)

答案 1 :(得分:0)

尝试以下代码

 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()
        }

答案 2 :(得分:0)

将此代码放入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;
}

答案 3 :(得分:0)

只需像这样使用

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