Swift:检查iOS是否在没有互联网的情况下连接到wifi

时间:2018-09-05 22:04:35

标签: swift networking wifi

我需要检查iPhone是否已连接至无法提供互联网连接的wifi网络。据我所知,Reachability等正在检查互联网连接,这不是我所需要的。

我要连接的设备是没有互联网功能的专有设备。我需要知道是否通过wifi连接到它。

1 个答案:

答案 0 :(得分:0)

// MARK: - Network Checker
func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}