7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

NWPathMonitorのハマりどころ

Posted at

currentPathはstartするまで正しい値が返らない

Reachbilityの気分でcurrentPathを呼ぶと上手く取れない

let monitor = NWPathMonitor()
print(monitor.currentPath.status) //unsatisfied

startすると正しい値になる

let monitor = NWPathMonitor()
monitor.start(queue: .global(qos: .background))
...
print(monitor.currentPath.status) //satisfied

NWPathMonitorはすぐに反映されない

start直後は正しい状態に反映されないことがある。

let monitor = NWPathMonitor()
monitor.start(queue: .global(qos: .background))
print(monitor.currentPath.status) //unsatisfied

感覚としては、viewDidLoad ~ viewDidAppearくらいの時間は必要そう。


  let monitor = NWPathMonitor()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    monitor.start(queue: .global(qos: .background))
  }
  
  override func viewDidAppear(_ animated: Bool) {
    print(monitor.currentPath.status) //satisfied
  }

これでも取れる

  let monitor = NWPathMonitor()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    monitor.start(queue: .global(qos: .background))
    DispatchQueue.main.async {
      print(self.monitor.currentPath.status)
    }
  }
7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?