NotificationCenter未通过网络更改触发

时间:2016-12-19 19:28:21

标签: swift

我想检测网络更改。例如,当从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")
        }
    }

我做错了吗?

3 个答案:

答案 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

它将起作用。