在 swift 中单击远程推送通知时调用特定的视图控制器

call a specific View Controller when remotepush notification is clicked in swift

我想在点击通知时在特定的视图控制器中显示推送通知,并且还想将数据从通知发送到视图控制器。我正在使用 swift 进行开发

你应该为你的视图控制器实现路由器,它将监听从应用委托发送的通知,他将决定做什么。这就是我的做法,可能是更好的解决方案。

正如@luzo 所指出的,通知是发送给视图控制器的方式,通知事件已经发生。该通知还有一个 userinfo 参数,该参数接受您希望与通知一起发送到视图控制器的数据字典。

在Swift3中,将此添加到点击按钮:

let center = NotificationCenter.default
center.post(name: Notification.Name(rawValue: "nameOfNotification"),
                    object: nil,
                    userInfo:["id":"data"])

并在viewcontroller中注册通知的id并添加函数引用:

    let center = NotificationCenter.default
    center.addObserver(forName:NSNotification.Name(rawValue: "nameOfNotification"), object:nil, queue:nil, using:notifDidConnect)

并添加函数实现:

 func notifDidConnect(notification:Notification) -> Void {
        guard let userInfo = notification.userInfo,
            let id  = userInfo["id"] as? String else {
               print("error occured")
               return
             }
        print("notification received")
    }