Hi! I am using NWPathMonitor to check the network connection, and only want it to monitor in one of the screens of my app. Hence, I created a NWPathMonitor in the corresponding view controller and attempt to turn on the monitor when the view appears, and turn off when the view disappear. I tried to use the .start and .cancel methods but couldn't get it done. Below are two versions of my experiment codes, and each of them get an issue. Can you help me to look at it?
Thank you!
Experiment code 1: cancel but network connection is still being checked. Not sure why I can still see the popup message warning the network connection.
private let networkMonitor: NWPathMonitor = NWPathMonitor()
private var networkMonitorQueue: DispatchQueue = DispatchQueue(label: "NetworkMonitorQueue")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.networkMonitor.start(queue: networkMonitorQueue)
self.networkMonitor.cancel()
self.networkMonitor.pathUpdateHandler = {
p in
if p.status != .satisfied {
DispatchQueue.main.sync {
Utilities.DisplayMessage(vController: self as UIViewController, mTitle: "Network Connection Error", mText: "This device is not connected to Internet. Stock reports will not be updated.")
}
}
}
}
Experiment code 2: not getting popup message about network any more, but in the XCode output I got error message when running the second .start command: nw_path_evaluator_set_queue Client error: set queue after starting
private let networkMonitor: NWPathMonitor = NWPathMonitor()
private var networkMonitorQueue: DispatchQueue = DispatchQueue(label: "NetworkMonitorQueue")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.networkMonitor.start(queue: networkMonitorQueue)
self.networkMonitor.cancel()
self.networkMonitor.start(queue: networkMonitorQueue)
self.networkMonitor.cancel()
self.networkMonitor.pathUpdateHandler = {
p in
if p.status != .satisfied {
DispatchQueue.main.sync {
Utilities.DisplayMessage(vController: self as UIViewController, mTitle: "Network Connection Error", mText: "This device is not connected to Internet. Stock reports will not be updated.")
}
}
}
}
NWPathMonitor
has a
cancel
method, not
stop
method. Once you cancel a path monitor, that specific object is done. You can’t start it again. You will need to create a new path monitor in
viewDidAppear(_:)
.
Oh, btw, you can remove
networkMonitorQueue
from your snippet. If you want the path update handler to run on the main queue, pass
.main
to
start(queue:)
.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"