3

I try to make NWPathMonitor an observable object that returns true if there is a network connection and false if not.

Can you help me because my solution doesn't work.

Thanks

import Foundation
import Network

class TestNetStatus: ObservableObject {

    let monitor = NWPathMonitor()
    let queue = DispatchQueue.global(qos: .background)

    @Published var connected: Bool = false
    private var isConnected: Bool = false

    init() {
        monitor.start(queue: queue)

        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                self.isConnected = true
            } else {
                self.isConnected = false
            }
        }

        self.connected = isConnected
    }
}

4

1 回答 1

6

you have to set the published variable on the main thread

class TestNetStatus: ObservableObject {

    let monitor = NWPathMonitor()
    let queue = DispatchQueue.global(qos: .background)

    @Published var connected: Bool = false
    private var isConnected: Bool = false

    init() {
        monitor.start(queue: queue)

        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                OperationQueue.main.addOperation {
                    self.isConnected = true
                    self.connected = self.isConnected
                }
            } else {
                OperationQueue.main.addOperation {
                    self.isConnected = false
                    self.connected = self.isConnected
                }            }
        }
    }
}

struct ContentView: View {

    @EnvironmentObject var data  : TestNetStatus

    var body: some View {
        VStack {
            Text ("Status")
            Text(data.connected ? "Connected" : "not connected")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(TestNetStatus())
    }
}

enter image description here

于 2020-05-06T02:39:09.980 回答