NotificationCenter中的推送通知在userinfo - Swift3中返回nil

时间:2016-10-04 10:10:58

标签: ios push-notification swift3

我已将源代码从Swift 2.2更新为Swift 3.0以进行推送通知。但我无法获得userinfo。它将返回零。 有人可以帮忙吗?

此处在app delegate中收到了推送通知:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        // Define identifier
        let notificationName = Notification.Name("PushNotificationMessageReceivedNotification")

        // Register to receive notification
        NotificationCenter.default.addObserver(self, selector: #selector(MenuViewController.remoteNotificationReceived), name: notificationName, object: userInfo)

        // Post notification
        NotificationCenter.default.post(name: notificationName, object: nil)
    }

在其他viewController中,我想收到推送通知并执行一些操作:

override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self

        NotificationCenter.default.addObserver(self, selector: #selector(MenuViewController.remoteNotificationReceived(_:)), name: NSNotification.Name(rawValue: "PushNotificationMessageReceivedNotification"), object: nil)

    }

func remoteNotificationReceived(_ notification: Notification)
    {
        print("Notification:\(notification.userinfo)");
}

1 个答案:

答案 0 :(得分:1)

发布通知时传递UserInfo 像这样: -

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        // Define identifier
        let notificationName = Notification.Name("PushNotificationMessageReceivedNotification")

        // Register to receive notification
        NotificationCenter.default.addObserver(self, selector: #selector(MenuViewController.remoteNotificationReceived), name: notificationName, object: userInfo)

        // Post notification
        NotificationCenter.default.post(name: notificationName, object: nil, userInfo :userInfo)
    }