Check for internet connection with Swift

前端 未结 21 1852
别跟我提以往
别跟我提以往 2020-11-22 05:59

When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

import Foundation
impo         


        
21条回答
  •  独厮守ぢ
    2020-11-22 06:08

    iOS12 Swift 4 and Swift 5

    If you just want to check the connection, and your lowest target is iOS12, then you can use NWPathMonitor

    import Network
    

    It needs a little setup with some properties.

    let internetMonitor = NWPathMonitor()
    let internetQueue = DispatchQueue(label: "InternetMonitor")
    private var hasConnectionPath = false
    

    I created a function to get it going. You can do this on view did load or anywhere else. I put a guard in so you can call it all you want to get it going.

    func startInternetTracking() {
        // only fires once
        guard internetMonitor.pathUpdateHandler == nil else {
            return
        }
        internetMonitor.pathUpdateHandler = { update in
            if update.status == .satisfied {
                print("Internet connection on.")
                self.hasConnectionPath = true
            } else {
                print("no internet connection.")
                self.hasConnectionPath = false
            }
        }
        internetMonitor.start(queue: internetQueue)
    }
    
    /// will tell you if the device has an Internet connection
    /// - Returns: true if there is some kind of connection
    func hasInternet() -> Bool {
        return hasConnectionPath
    }
    

    Now you can just call the helper function hasInternet() to see if you have one. It updates in real time. See Apple documentation for NWPathMonitor. It has lots more functionality like cancel() if you need to stop tracking the connection, type of internet you are looking for, etc. https://developer.apple.com/documentation/network/nwpathmonitor

提交回复
热议问题