[英]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:这是场景:
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.