NotificationCenter观察员未收到帖子

时间:2016-12-02 10:21:10

标签: swift swift3 nsnotificationcenter

我已经尝试了很长时间才能收到观察员收到的通知帖子,但每次尝试都会让我失望。我把观察者放到我的根视图控制器中,是一个嵌入式标签控制器,并试图让其中一个标签控制器发送一个帖子供它接收,但无济于事。我不能,为了我的生活,想出这个,我真的很喜欢,因为通知可能会非常有用!

这是我的代码:

的ViewController

let myNotification = Notification.Name(rawValue:"categoryChange")

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()
    let nc = NotificationCenter.default
    nc.addObserver(forName:myNotification, object:"test", queue:nil, using:test)
}

func test(notification:Notification) -> Void {
    print("Yo")
}

这是我的 DashboardController

override func viewDidLoad() {
    super.viewDidLoad()
    let myNotification = Notification.Name(rawValue:"categoryChange")
    let nc = NotificationCenter.default
    nc.post(name:myNotification,
            object: nil,
            userInfo:["message":"Hello there!"])
}

我已尝试将观察者放入init viewDidLoadviewDidAppear,而帖子位于viewDidLoad,我反之亦然。到目前为止,没有任何工作,我无法弄清楚原因。

提前感谢任何可以提供帮助的人!

2 个答案:

答案 0 :(得分:3)

它适用于我的项目。

发布通知

 let dic: [String:AnyObject] = ["news_id": 1 as AnyObject,"language_id" : 2 as AnyObject]
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationKeyIndentifier"), object: dic)

通知观察员

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

            if let dic = notification.object as? [String: AnyObject]{

                if let language_id = dic["language_id"] as? Int{

                    if let news_id = dic["news_id"] as? Int{
                        print(language_id)
                        print(news_id)
                    }
                }
            }
        }

答案 1 :(得分:2)

当您在test添加观察者时,您的问题是您正在使用String参数传递objectNotificationCenter}。

(来自文档)对象:

  

观察者想要接收通知的对象;也就是说,只有此发件人发送的通知才会传递给观察者。

     

如果您通过nil,通知中心不会使用通知的发件人来决定是否将其发送给观察者。

因此,这是因为您没有在object的帮助下发布通知而导致您的通知未被调用的原因,只需将object设置为nil即可。

nc.addObserver(forName:myNotification, object:nil, queue:nil, using:test)
相关问题