在这里,我想用addObserver检查一下我是否有网络连接。
我使用了https://github.com/ashleymills/Reachability.swift的reachability swift 5.0,并使用了下面的代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let reachability = try! Reachability()
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability?.startNotifier()
print("start notifierrrr")
}catch{
print("could not start reachability notifier")
}
...
}当我打开/关闭我的wi-fi时,函数根本没有调用
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.currentReachabilityStatus {
case .reachableViaWiFi:
print("Reachable via WiFi bbb")
case .reachableViaWWAN:
print("Reachable via WWAN bbb")
case .notReachable:
print("Network not reachable bbb")
}
}注:我使用的是真实设备iPhone7和ReachabilitySwift (5.0.0)
发布于 2020-08-13 14:43:34
public convenience init(hostname: String,
queueQoS: DispatchQoS = .default,
targetQueue: DispatchQueue? = nil,
notificationQueue: DispatchQueue? = .main) throws {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else {
throw ReachabilityError.failedToCreateWithHostname(hostname, SCError())
}在start notifier()之前使用主机名(www.google.com)初始化可达性
https://stackoverflow.com/questions/63328464
复制相似问题