在我的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时,它什么都不做。
答案 0 :(得分:2)
我需要强烈引用Reachability实例!所以我应该在课堂上宣布它。
答案 1 :(得分:1)
只有在您直接调用此方法时,它才会验证您的网络。如果您希望收到有关网络可更改性更改的通知,则应使用可更新性通知。
观察员通知。
//declare this property where it won't go out of scope relative to your listener
let reachability = Reachability()!
//declare this inside of viewWillAppear
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:",name: ReachabilityChangedNotification,object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
处理更改:
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
} else {
print("Network not reachable")
}
}
退订:
reachability.stopNotifier()
NSNotificationCenter.defaultCenter().removeObserver(self,
name: ReachabilityChangedNotification,
object: reachability)
答案 2 :(得分:0)
在Swift 4中,当可执行的Clouser无法执行时,我遇到了问题。 我发现所有通知都应在主队列中传递。
使用下面的代码解决
//在文件顶部声明此属性,因此范围将保留。
ConfigurationAdmin