在我的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实例的强烈参考!所以我应该在课堂上宣布它。
只有在您直接调用此方法时,它才会验证您的网络。如果您希望收到有关网络可更改性更改的通知,则应使用可更新性通知。
观察者通知。
//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)
在Swift 4中,我发现whenReachable clouser没有执行时出现问题。我发现所有通知都应该在主队列中提供。
解决使用下面的代码
//在文件顶部声明此属性,因此范围将保留。
let reachability = Reachability()!
func setUpReachability()
{
//declare this property where it won't go out of scope relative to your listener
DispatchQueue.main.async {
self.reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
self.self.reachability.whenUnreachable = { _ in
print("Not reachable")
}
do {
try self.reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
}