简体   繁体   中英

How to check network reachability when the device is connected to some hotspot and that hotspot's mobile data is off

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

  }

}

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, wierdEthe.net, loopback, other.

See documentation on: NWInterface.InterfaceType

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM