等到检查互联网连接 (Xcode 11)

Wait until internet connection is checked (Xcode 11)

我想检查设备是否已连接到互联网。为此,我等到得到结果(真或假)。这是我的代码:

import Foundation
import Network


let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "Monitor")

var connected = false

func checkConnection(completion:@escaping (Bool) -> () ) {
    DispatchQueue.main.async {
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                connected = true
            } else {
                connected = false                    
            }
        }
        monitor.start(queue: queue)
        completion(true)
    }
}

checkConnection { (status) in
    if status {
        print(connected)
    }
}

我不明白为什么它不起作用。我预计 connected 的值会发生变化,具体取决于我是否连接到互联网。相反,connected 的值仍然等于 false.

有人有想法吗? 谢谢

我找到了另一种更简单的方法:class 验证互联网连接(wifi 或蜂窝网络):

import SystemConfiguration

public class CheckInternet{

    class func Connection() -> 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(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            [=10=].withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }


        // Working for Cellular and WIFI
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        let ret = (isReachable && !needsConnection)

        return ret


    }

}

然后,在您的代码中检查(并等待)连接:

func checkConnection(completion:@escaping (Bool) -> () ) {
    DispatchQueue.main.async {

        if CheckInternet.Connection(){
            print("Internet connection is on.")
            self.go = true
        } else {
            self.go = false
            print("There's no internet connection.")
        }
        completion(true)
    }
}


checkConnection { (status) in
    if status {
        if self.go {
            // your code
        } else {
            // your code
        }

    }
}