swift 监测网络状态 Reachability
2020-04-20 本文已影响0人
喵喵粉
第三方库github Reachability
- 直接使用
AppDelegate.swift
fileprivate var reachability: Reachability?
fileprivate func checkNetworkState() {
reachability = try! Reachability()
reachability?.whenReachable = { reach in
switch reach.connection {
case .wifi:
DebugLog("Reachable via WiFi")
case .cellular:
DebugLog("Reachable via Cellular")
case .unavailable, .none:
fallthrough
default:
DebugLog("Network not reachable")
}
}
reachability?.whenUnreachable = { _ in
DebugLog("Not reachable")
}
do {
try reachability?.startNotifier()
} catch {
DebugLog("Unable to start notifier")
}
}
- 封装一层:
AppDelegate.swift
ReachableManager.shared.checkNetworkState()
ReachableManager.swift
import Foundation
import Reachability
class ReachableManager {
///不可用
var stateUseless: Bool = true
//userId 未登录-1
static let shared = ReachableManager()
fileprivate var reachability: Reachability?
func checkNetworkState() {
guard let reachability = try? Reachability() else { return }
self.reachability = reachability
reachability.whenReachable = { reach in
switch reach.connection {
case .wifi:
DebugLog("Reachable via WiFi")
self.stateUseless = false
case .cellular:
DebugLog("Reachable via Cellular")
self.stateUseless = false
case .unavailable, .none:
fallthrough
default:
DebugLog("Network not reachable")
self.stateUseless = true
}
}
reachability.whenUnreachable = { _ in
DebugLog("Not reachable")
self.stateUseless = true
}
do {
try reachability.startNotifier()
} catch {
DebugLog("Unable to start notifier")
}
}
deinit {
DebugLog("reachability.stopNotifier()")
reachability?.stopNotifier()
}
}