我想检测网络更改。例如,当从wifi切换到4G或返回时。但是我的代码没有检测到这些变化。应用程序启动后,我只获得了一些输出。
我有这段代码:
import ReachabilitySwift
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(self.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")
}
}
我做错了吗?
答案 0 :(得分:2)
action方法接受一个参数,因此选择器必须是
#selector(reachabilityChanged(_:)) // self is not needed
该方法本身应该是
func reachabilityChanged(_ notification: Notification) {
答案 1 :(得分:0)
选择器错误
更改此
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: ReachabilityChangedNotification,object: reachability)
到
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:),name: ReachabilityChangedNotification,object: reachability)
我希望这会奏效。
以及
func reachabilityChanged(note: NSNotification) {
到
func reachabilityChanged(note: NSNotification) {
答案 2 :(得分:0)
name
是错误的。更改
name: ReachabilityChangedNotification
到
name: NSNotification.Name.reachabilityChanged
或
name: .reachabilityChanged
它将起作用。