检查swift中是否提供互联网连接

时间:2014-06-20 19:53:48

标签: ios swift

是否有Apple框架捆绑包可以检测是否存在互联网连接?目前,我的应用程序在尝试在没有互联网连接的情况下对用户的位置进行地理定位时崩溃。

/*inside locationManager didUpdateLocations method*/
var currentLocation:CLLocation? = locations[0] as? CLLocation
geocoder = CLGeocoder()
//Crashes on line below when there isn't an internet connection
//Need to add function to check if internet connection is live 
//Before running reverseGeocodeLocation
geocoder.reverseGeocodeLocation (currentLocation,handleGeocode)

我对swift和ios编程有点新意 - 我道歉。

3 个答案:

答案 0 :(得分:20)

不是一个成熟的网络检查库,但我找到了this检查网络可用性的简单方法。我设法把它翻译成Swift,最后是代码。

import Foundation
import SystemConfiguration

public class Reachability {

    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) ? true : false
    }

}

适用于3G和WiFi连接。我还用一个有效的例子将它上传到我的Github。如果您正在寻找一种纯粹在Swift中检查网络可用性的简单方法,您可以使用它。

答案 1 :(得分:4)

使用Babatunde的代码示例,但这里是Swift 2.0的更新版本和错误处理: 编辑:还将Google的URL更改为iOS 9的HTTPS。 EDIT2:原始文章:http://www.brianjcoleman.com/tutorial-check-for-internet-connection-in-swift/

    return sequelize.transaction({
      isolationLevel: "SERIALIZABLE",
      autocommit: false
    },function (t) {

      return sequelize.query('DELETE FROM Task WHERE id=:id',
      {
        replacements:{"id":id},
        type: sequelize.QueryTypes.SELECT
      })
      .then(function () {
        // the query was successful but I still want to roll back
        t.rollback();
      });
   });

答案 2 :(得分:1)

由于Reachability尚未完全移植到swift,您可以使用下面的示例代码检查互联网连接:

public class Reachability {
/**
 * Check if internet connection is available
 */
class func isConnectedToNetwork() -> Bool {
    var status:Bool = false

    let url = NSURL(string: "http://google.com")
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    var response:NSURLResponse?

    var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode == 200 {
            status = true
        }
    }

    return status
  }
}

请参阅以下函数的示例用法:

// Check if internet is available before proceeding further
    if Reachability.isConnectedToNetwork() {
        // Go ahead and fetch your data from the internet
        // ...
    } else {
        println("Internet connection not available")

        var alert = UIAlertView(title: "No Internet connection", message: "Please ensure you are connected to the Internet", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }