iOS13 网络不可用怎么查看?

How to check when the network is unavailable in iOS 13?

我添加了一些逻辑来处理网络不可用,但我很难触发错误处理程序。我正在使用 URLError networkUnavailableReason 是正确的吗?

DataService.shared.GetMyData(completion: {(result) in
    DispatchQueue.main.async {
        switch result {
            case .success(let data):


                break
            case .failure(let error):
                print(error)
                if let error = error as? URLError, error.networkUnavailableReason == .constrained  {

                    self.showAlert()
                }

                break;
        }
    }
})

您可以使用网络监视器NWPathMonitor来检查网络是否可用。我通过为它创建一个结构来使用这样的一个:

// make sure to import Network in your file when you do this
struct NetworkMonitor {
    static let monitor = NWPathMonitor()
    static var connection = true
}

然后就这样用了,想在哪里开始监控:

NetworkMonitor.monitor.pathUpdateHandler = { path in
               if path.status == .satisfied {
                    print("connection successful")
                    NetworkMonitor.connection = true
                    // then respond to successful connection here, I used a notification and this connection bool
              } else {
                    print("no connection")
                    NetworkMonitor.connection = false
                    // respond to lack of connection here
               }
          }

          let queue = DispatchQueue(label: "Monitor")
          NetworkMonitor.monitor.start(queue: queue)