在我的 viewDidLoad()
函数中,我调用了这个方法:
//MARK: Reachability
func startReachability(){
//declare this property where it won't go out of scope relative to your listener
do{
let reachability = try Reachability.reachabilityForInternetConnection()
reachability.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
}
reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
print("Not reachable")
}
}
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
但它不起作用。它只调用一次 whenReachable()
和 whenUnreachable()
并且当我关闭和打开 Wi-Fi 时它什么也不做。
最佳答案
我需要对 Reachability 实例的强烈引用!所以我应该在类里面声明它。
关于ios - ReachabilitySwift 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39568144/