在Swift2中检查设备是否已连接到互联网

时间:2016-03-07 09:47:59

标签: ios swift

我试图找到一种方法来检查我的应用程序是否与我的应用程序的互联网连接。我已尝试使用您在GitHub上可以找到的各种Reachability库,这会导致我的项目出现编译错误。 (由于某些原因,使其他库不可用)并且我还尝试了JustHTTP库向http://www.google.com发出GET请求,但每次都失败。

我不确定这里的问题是什么,但我想了解一些人在允许用户使用该应用程序之前如何验证与互联网的连接。

此问题已标记为重复,并链接到使用Reachability提供的AshleyMills库的问题。我已经声明我已经尝试过使用这些库,但是我的项目中没有冲突错误。此问题上提供的GET请求代码也已过期,并且不适用于SWIFT2。这个链接的问题也假设我不需要支持iOS 9下的任何东西,这似乎是一种不好的做法。我的最低支持是iOS8

4 个答案:

答案 0 :(得分:1)

Swift 2.x(需要可达性)

do {
    let reachable = try Reachability.init(hostname: "www.google.com")
    if(reachable.currentReachabilityStatus == Reachability.NetworkStatus.ReachableViaWWAN){
        //Device is connected thru 3G/4G/LTE
    }else if(reachable.currentReachabilityStatus == Reachability.NetworkStatus.ReachableViaWiFi){
        //Device is connected thru WiFi
    }else{
        //Device is not connected to the internet
    }
}catch{
    //Device is not connected to the internet
}

您可以获得可达性here

答案 1 :(得分:0)

Reachability.swift 添加到您的项目中。

尝试以下代码。

    do
    {
        let connected: Bool = try Reachability.reachabilityForInternetConnection().isReachable()

        if connected == true
        {
            print("Internet connection OK")
        }
        else
        {
            print("Internet connection FAILED")
            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        }
    }
    catch
    {
        print("Handle Exception")

    }

答案 2 :(得分:0)

此代码可能有所帮助。您需要Reachability lib,此代码段可以为您提供示例,以检查您的设备是通过WiFi还是通过4G / 3G / LTE上网

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)

如果您的请求一直失败,可能是因为您没有通过https而是通过http执行。它与iOS 9上的ATS有关 - 这个博客很好地解释了如何禁用(如果你想 - 不推荐)ATS http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/

相关问题