Samuil Banti
Samuil Banti

Reputation: 1795

Swift network monitor switches .satisfied and .unsatisfied statuses

I'm trying to monitor the network access of an iOS app.

When I run the simulator for a first time with wifi turned ON I get the right message "We're connected!".

But when I switch OFF the wifi I get the same message "We're connected!".

If I switch it on again I get the "No connection." message.

If I continue to switch the network on and off I get the opposite status of the actual state of the wifi.

Any ideas what am I doing wrong? Here's the code:

import Foundation
import Network

final class NetworkMonitor: ObservableObject {
    
    let queue = DispatchQueue(label: "NetworkMonitor")
    let monitor = NWPathMonitor()
    
    init() {
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                print("We're connected!")
            } else {
                print("No connection.")
            }
        }
        monitor.start(queue: queue)
    }
    
}

Upvotes: 5

Views: 1448

Answers (1)

Samuil Banti
Samuil Banti

Reputation: 1795

@tromgy was right that the code in the question seems to work on actual device but I'll post my workaround here.

NOTE: The environment check for a simulator seems optional to me but let me know if you have a different opinion.

import Foundation
import Network

final class NetworkMonitor: ObservableObject {

    static let shared = NetworkMonitor()
    let queue = DispatchQueue(label: "NetworkMonitor")
    let monitor = NWPathMonitor()
    @Published public private(set) var isConnected: Bool = false
    private var hasStatus: Bool = false
    
    init() {
        monitor.pathUpdateHandler = { path in
            #if targetEnvironment(simulator)
                if (!self.hasStatus) {
                    self.isConnected = path.status == .satisfied
                    self.hasStatus = true
                } else {
                    self.isConnected = !self.isConnected
                }
            #else
                self.isConnected = path.status == .satisfied
            #endif
            print("isConnected: " + String(self.isConnected))
        }
        monitor.start(queue: queue)
    }

}

Upvotes: 2

Related Questions