简体   繁体   English

当设备连接到某个热点并且该热点的移动数据已关闭时,如何检查网络可达性

[英]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.我正在使用 Almofire 来实现网络可达性。 Here is the scenario:这是场景:

  1. Connect the iPad/iPhone with mobile hotspot.将 iPad/iPhone 连接到移动热点。
  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.现在关闭移动数据,但iPad/iPhone与热点设备之间仍然存在热点连接。
  4. Now check the.network reachability status, it will again return true.现在检查网络可达性状态,它会再次返回 true。 Ideally it should return false, as the server is not reachable.理想情况下它应该返回 false,因为服务器不可访问。
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 .也许尝试用NWPathMonitor替换 reachability 。

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.一个 Boolean 指示路径是否使用被认为是昂贵的接口,例如蜂窝或个人热点。

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.这为您提供了更多选项,例如:.wifi、wierdEthe.net、环回等。

See documentation on: NWInterface.InterfaceType请参阅以下文档: 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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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