Search code examples
iosswiftwifi

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


I need an event or like an observer while switching between wifi networks or wifi to cellular and vice versa. Can anybody help me with it? I am uploading a video file and while uploading I am switching between wifi networks or auto-switch between cellular to wifi. So need an event for the same.


Solution

  • It is included in the example on the Reachability github page

    //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")
        }
    

    And the method

    @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")
      }
    }