Search code examples
iosswiftreachability

Observe WiFi / 3G changes


Is it possible to observe when the user switch between WiFi and cellular data (3G/4G)?

Maybe something in Reachability, but I don't know what.


Solution

  • The easiest way I think is import CoreTelephony and observe CTRadioAccessTechnologyDidChangeNotification and then switch over that like this:

    let networkInfo = CTTelephonyNetworkInfo()
    let radio = networkInfo.currentRadioAccessTechnology
    
    guard let currentRadio = radio else {
       print("No radio info available")
       return
    }
    
    switch currentRadio {
       case CTRadioAccessTechnologyLTE,
            CTRadioAccessTechnologyHSDPA: //3.5G "T-Mobile 4G"
           print("This is 4G / LTE")
       case CTRadioAccessTechnologyeHRPD, //3.5G "Verizon 3G"
            CTRadioAccessTechnologyHSUPA,
            CTRadioAccessTechnologyWCDMA,
            CTRadioAccessTechnologyCDMAEVDORev0,
            CTRadioAccessTechnologyCDMAEVDORevA,
            CTRadioAccessTechnologyCDMAEVDORevB:
          print("This is 3G")
       case CTRadioAccessTechnologyGPRS,
            CTRadioAccessTechnologyCDMA1x
            CTRadioAccessTechnologyEdge:
          print("This is 2G")
       default:
          print("Unknown cellular network type")
       }
    

    If you listen for that notification while also using standard Reachability, you can use this switch to get cell network type. You will need currentReachabilityStatus to independently check for a WiFi connection. As far as I am aware, in Swift you need to set up a bridging header to use Apple's Reachability class but there are Swift implementations available as well on github.