2016-03-07 104 views
1

我试图找到一种方法来检查,看看是否我的应用程序有我的应用程序到互联网的连接。我试过使用各种你可以在GitHub上找到的Reachability库,它们会导致我的项目编译错误。 (由于某种原因,使其他库不可用),我也尝试使用JustHTTP库来发起对http://www.google.com的GET请求,但每次都会失败。检查设备是否连接到互联网的Swift2

我不太确定这个问题是在这里什么,但我想知道如何一些你去让用户使用应用程序之前验证到互联网的连接。

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

+1

看到这个链接它可以帮助你http://stackoverflow.com/questions/30743408/check-for-internet-connection-in-swift-2-ios-9 –

+0

@ Anbu.Karthik - 不起作用用于蜂窝网络。 – Hobbyist

+0

哦,但我不收乌尔问题.... –

回答

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

    } 
0

此代码可能会有所帮助。你需要的可达性的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; 
} 
+0

如果这是由AshleyMills提供的'Reachability'库,它不会在编译我的项目,因为它会导致与其他图书馆冲突。 – Hobbyist

0

斯威夫特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