简体   繁体   中英

can't receive notifications from Notification Center

I have a simple app: first VC:

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.post(name: NSNotification.Name("test"), object: nil, userInfo: nil)
}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "secondVC")
    self.present(vc, animated: true, completion: nil)
}

}

second VC:

class SecondVC: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(SecondVC.testFunc(notification:)), name: NSNotification.Name("test"), object: nil)
}

@objc func testFunc(notification: NSNotification) {        
    print("!!!!!!!!!!!!!!!!")
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

}

and I never saw the "!!!!!!!!!!!!!!!!", what am I doing wrong?

What is happening is that you're posting the notification in a viewDidLoad from the first view controller, then later on viewDidAppear you're pushing your second view controller and then subscribing to the notification center. At that point your notification has already being fired, hence you're not receiving it. Your second view controller will only receive notification that are fired post its subscription to the notification center. Create a timer that will fire the notification in a couple of seconds after view did appear pushes your second view controller and you will see it working

In your above mentioned code, you are posting the notification first & then adding the observer for it. So, in order to call testFunc method you need to addObserver first then post the notification.

You can add few seconds delay in firstVC for posting Notification.

override func viewDidLoad() {
      super.viewDidLoad()
      DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
           NotificationCenter.default.post(name: NSNotification.Name("test"), object: nil, userInfo: nil)
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM