I'm trying to check for the internet connection in my app, and currently, I have this code:
private let monitor: NWPathMonitor
monitor.pathUpdateHandler = { [weak self] path in
print(path.status)
self?.isConnected = path.status == .satisfied
}
However, this does not work. Specifically, the print does not print out the value in the debug console.
Could you please tell me what I have done wrong?
Thank you.
here is my (SwiftUI, sorry) test code that works for me. You can probably recycle some of the code for your purpose.
import SwiftUI
import Foundation
import Network
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
let monitor = NWPathMonitor()
var body: some View {
Text("testing")
.onAppear {
let queue = DispatchQueue(label: "monitoring")
monitor.start(queue: queue)
monitor.pathUpdateHandler = { path in
print(path.status)
if path.status == .satisfied {
print("-----> YES connected")
} else {
print("-----> NOT connected")
}
}
}
}
}
You can also use specific monitor
, such as let monitor = NWPathMonitor(requiredInterfaceType: .wifi)