小编典典

在Swift中检查互联网连接可用性

swift

是否可以使用Swift检查互联网连接是否可用?

我知道有很多第三方库可以执行此操作,但是它们都是用Objective-C编写的。我正在寻找Swift的替代方案。


阅读 393

收藏
2020-07-07

共1个答案

小编典典

如评论中所述,尽管可以在Swift中使用Objective-C库,但我想要一个更纯粹的Swift解决方案。现有的AppleReachability类和其他第三方库对于我来说转换为Swift似乎太复杂了。我用Google搜索了更多内容,然后发现本文显示了一种检查网络可用性的简单方法。我着手将其翻译为Swift。我遇到了很多麻烦,但是由于来自的MartinR,我设法解决了这些麻烦,并最终在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
    }

}

对于Swift > 3.0

public class Reachability {
    public func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return false
        }

        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return false
        }
        if flags.isEmpty {
            return false
        }

        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)

        return (isReachable && !needsConnection)
    }
}

这适用于3G和WiFi连接。我还通过一个工作示例将其上传到了我的GitHub

2020-07-07