NotationMaster
NotationMaster

Reputation: 410

Why does NWPathMonitor status is always satisfied?

When there is no connection I get an error from the URL Session saying that the request timed out.
I’m using the Network protocol to check for connectivity before hand but apparently this is not working as when I am calling this inside viewDidLoad:

static func startUpdateProcess() {
    let monitor = NWPathMonitor()

    monitor.pathUpdateHandler = { path in
        if path.status == .satisfied {
            print("Good! We are connected!")
            Helper.createDownloadTask()
        } else {
            print("No connection. Local file not updated!")
        }
    }
    let queue = DispatchQueue(label: "Monitor")
    monitor.start(queue: queue)
}

...I get “Good! We are connected!”. Shouldn’t the path not be satisfied if there is no connection and therefore trigger the else statement?
FYI the createDownloadTask() questions the API and downloads the required data.

Can you tell me what is wrong here and what could I do to get to the else statement if the path is not satisfied?

Thank you!

Upvotes: 3

Views: 3953

Answers (2)

NotationMaster
NotationMaster

Reputation: 410

Credit to user May Rest in Peace for pointing me to the right direction.

Despite the Documentation being silent on the Network Protocol, it seems that the status property of the NWPath class, an enumeration of type NWPath.Status, returns .satisfied as long as the device is connected to a network, regardless of whether that network is working, transmitting data, or not.

The only way the else statement above could be triggered would have been by deactivating Wi-Fi and/or Cellular data or disconnecting from any network before launching the app.

All those properties are listed in the Documentation but none of them has a description or a discussion attached. This article by user @twostraws allowed me to create the first part of that code.

Upvotes: 2

May Rest in Peace
May Rest in Peace

Reputation: 2207

Reference to the instance of NWPathMonitor (aka monitor in your scenario) needs to be retained.

You could make it a strong property by making monitor a class level property so that its lifecycle is the same as the place you are referring it from. It looks like the monitor object is being released effectively stopping the callbacks for network status monitoring.

Upvotes: 1

Related Questions