带有 NWPathMonitor 的 ObservableObject

ObservableObject with NWPathMonitor

我尝试使 NWPathMonitor 成为一个可观察的对象,returns如果有网络连接则为真,否则为假。

你能帮我吗,因为我的解决方案不起作用。

谢谢

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
    }
}

你必须在主线程上设置发布的变量

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())
    }
}