【问题标题】:Check if internet connection availabile in swift [duplicate]检查 swift 中是否有可用的互联网连接 [重复]
【发布时间】:2014-06-20 19:53:48
【问题描述】:

是否有用于检测是否有互联网连接的 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 编程有点陌生 - 抱歉。

【问题讨论】:

  • 由于 Swift 可以向 Objective-C 对象发送消息,因此其他问题的答案也适用于此处。如果您无法将该答案集成到您的项目中,请随时创建一个新问题寻求帮助。
  • Rob,我正在寻找一个快速的解决方案,而不是一个 Objective-c 的解决方案......在我看来,我希望我的所有代码都在 swift 而不是在 Objective-c 中,这样更容易以 1 种语言维护。我相信长期所有代码都必须“移植”到swift。我想我必须尽快重写 Reachability 类才能做到这一点?
  • 也许你可以用 Swift 重写它。由于它建立在需要注册回调函数的 C 框架(SystemConfiguration)之上,因此它需要的不仅仅是 Swift 初学者的知识。
  • 用 Swift 编写所有代码是个好主意,但是 Apple 为我们在这两种语言之间架起了一座桥梁,遇到了很多麻烦。 Swift 是专门为与 Objective-C 一起使用而创建的——不要逃避这一点。
  • @PHPDave cocoa touch api 是用 ObjC 编写的,很长一段时间都不会去任何地方。我喜欢 Swift,如果你学习 ObjC,你会做得更好

标签: ios swift


【解决方案1】:

不是一个成熟的网络检查库,但我发现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 中检查网络可用性的简单方法,您可以使用它。

【讨论】:

  • 仅供参考,这也适用于 OS X。
  • 如果我的 3G 已开启,但我没有数据包怎么办?它会返回真实吗?
【解决方案2】:

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

import Foundation
import SystemConfiguration

public class Reachability {

    // Check if internet connection is available

    class func isConnectedToNetwork() -> Bool {

        var status:Bool = false

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

        var response:NSURLResponse?

        do {
            let _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 要在上述解决方案中工作,您必须在 info.plist 文件中的 NSAppTransportSecurity 字典下添加:“NSAllowsArbitraryLoads 键为 YES。”否则代码将不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2011-05-13
    • 2014-10-13
    • 2011-09-02
    相关资源
    最近更新 更多