我使用 Almofire 来实现网络可达性。这是场景:
class ReachabilityManager: NSObject {
static let shared = ReachabilityManager()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "my.server.url")
var isReachable : Bool {
return reachabilityManager?.isReachable ?? false
}
}
也许尝试用
NWPathMonitor
替换可达性。
它更可靠,给您更多选择。
这是一个例子:
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)
}
您还可以检查用户是否正在使用蜂窝数据或连接到热点:
path.isExpensive
根据文档:
一个布尔值,指示路径是否使用以下接口 被认为昂贵,例如蜂窝或个人热点。
此外,您可以检查各种连接要求或类型:
let monitor = NWPathMonitor(requiredInterfaceType: .cellular)
这为您提供了更多选项,例如:.wifi、wierdEthernet、环回、其他。
请参阅以下文档:
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")
}