我如何检查数据上传之间的 wifi 开关

How do i check the wifi switch in between my data uploading

在 wifi 网络或 wifi 与蜂窝网络之间切换时,我需要一个事件或喜欢一个观察者,反之亦然。有人可以帮我吗? 我正在上传视频文件,上传时我正在 wifi 网络之间切换或在蜂窝网络与 wifi 之间自动切换。所以需要一个相同的事件

检查设备是否连接,可以使用NWPathMonitor,像这样:

import Network

struct ConnectivityMonitor {
    static let monitor = NWPathMonitor()

    static func setup() {
        ConnectivityMonitor.monitor.pathUpdateHandler = { path in
            //path.isExpensive tells you whether the user is using cellular data as opposed to wifi. "true" if cellular data.
            
            if path.status == .satisfied {
                //Connected
            } else {
                //Not connected
            }
        }

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

它包含在可达性 github 页面的示例中

//declare this property where it won't go out of scope relative to your listener
let reachability = try! Reachability()

//declare this inside of viewWillAppear

    NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do{
      try reachability.startNotifier()
    }catch{
      print("could not start reachability notifier")
    }

和方法

@objc func reachabilityChanged(note: Notification) {

  let reachability = note.object as! Reachability

  switch reachability.connection {
  case .wifi:
      print("Reachable via WiFi")
  case .cellular:
      print("Reachable via Cellular")
  case .unavailable:
    print("Network not reachable")
  }
}