I need to check the network connection with NWPathMonitor.
import Foundation
import Network
class NetworkViewModel: ObservableObject {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "NetworkViewModel")
@Published var isConnected = false
var connectionDescription: String {
if isConnected {
return "You are connected."
} else {
return "You are NOT connected."
}
}
init() {
monitor.pathUpdateHandler = { path in
DispatchQueue.main.async {
self.isConnected = path.status == .satisfied
}
}
monitor.start(queue: queue)
}
}
import SwiftUI
struct ContentView: View {
@StateObject private var networkViewModel = NetworkViewModel()
var body: some View {
VStack {
}
.onAppear {
if networkViewModel.isConnected {
print("You are connected.")
}
else {
print("You are NOT connected.")
}
}
}
}
So there is nothing special, not at all. Yet, if I test it with a totally new Xcode project for iOS, it fails and return !isConnected. I've tested it with a macOS application. And it fails. I've tested it with an actual device. It fails. I've tested it with an old project. It still does work. I have no mere idea why new Xcode projects all fail to detect the WiFi connection. This is a total nightmare. Does anybody have a clue? thanks.
If they are not connected, I just show some text … never showing the purchase list.
We recommendation against writing code like this. The problem is that NWPathMonitor
can generate both false positive and false negatives:
-
The existence of false positives means that your code has to handle the case where you think networking is available but it isn’t. And if you’re gonna write that code anyway, you might as well relying on it all the time.
-
The possibility of false negatives means that you might end up blocking the user from doing something that would’ve otherwise worked.
If, despite the above, I decide to continue down this path then:
-
Test your app in situations where
NWPathMonitor
returns a false positive. For example, turn off WWAN, then have your device join a Wi-Fi network, and then disconnect the Wi-Fi network from the wider Internet. -
Use
NWPathMonitor
in an advisory capacity only. Don’t block user operations based on its result.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"