skip to Main Content

I am using the Almofire for the network reachability. Here is the scenario:

  1. Connect the iPad/iPhone with mobile hotspot.
  2. Now turn on the mobile data, and check the network reachability status. It will return true. That is fine
  3. Now turn off the mobile data, but still there is hotspot connection between the iPad/iPhone and the hotspot device.
  4. Now check the network reachability status, it will again return true. Ideally it should return false, as the server is not reachable.
class ReachabilityManager: NSObject {

  static let shared = ReachabilityManager()

  let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "my.server.url")

  var isReachable : Bool {

    return reachabilityManager?.isReachable ?? false

  }

}

2

Answers


  1. Maybe try replacing reachability with NWPathMonitor.

    It has been more reliable and gives you more options.

    Here’s an example:

    import Network 
    
    let monitor = NWPathMonitor()
    
    func monitorNetwork() {
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                connectionAvailable = true
            } else {
                connectionAvailable = false
            }
        }
        let queue = DispatchQueue(label: "Net")
        monitor.start(queue: queue)
    }
    

    You can also check if user is using cellular data or is connected to a hotspot:

    path.isExpensive
    

    As per documentation:

    A Boolean indicating whether the path uses an interface that is
    considered expensive, such as Cellular or a Personal Hotspot.

    Furthermore you can check various connection requirments or types:

    let monitor = NWPathMonitor(requiredInterfaceType: .cellular)
    

    This gives you more options like: .wifi, wierdEthernet, loopback, other.

    See documentation on: NWInterface.InterfaceType

    Login or Signup to reply.
  2. let reachability = Reachability()!

    //This function is find to wifi or Cellular network
    reachability.whenReachable = { reachability in
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    
    //When Network is Off This Function Call
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }
    
    //This code is automatically call when network is on.
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search