如何在推送通知中获取数据?

时间:2019-10-02 04:48:19

标签: ios swift firebase push-notification firebase-cloud-messaging

我是推送通知的新手,我设法使推送通知生效。现在,只要有推送通知到来,如果我按它,应用程序就会打开并进入页面。

这是我的推送通知消息

{"to":"eHPnnkSDzWk:APA91bHs...","data":{"message":"test notification","type":"5"}}

这些是类型

Gallery ( Type = 1 )
Messenger ( Type = 4 )
Events ( Type = 5 )
News ( Type = 6 )

这是我的didReceiveRemoteNotification函数

    func application(_ application: UIApplication, didReceiveRemoteNotification 
userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: @escaping 
(UIBackgroundFetchResult) -> Void) {

        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }

这是我的问题,当用户单击推送通知时,如何从推送通知中获取此TYPE,然后在应用上打开特定页面?

(抱歉,这听起来很傻,但这是我第一次尝试这样做,我尝试环顾四周,但找不到正确的答案)

2 个答案:

答案 0 :(得分:1)

只需使用下面的代码即可通过测试

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

        if let dict = userInfo as? [String:Any] {
            if let dataDict = dict["data"] as? [String:Any],let type = dataDict["type"] as? String{
                print(type)
            }
        }
    }

答案 1 :(得分:0)

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    let userInfo = notification.request.content.userInfo

    guard
        let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
        let alert = aps["alert"] as? NSDictionary,
        let body = alert["body"] as? String,
        let title = alert["title"] as? String
        else {
            // handle any error here
            return
        }

    print("Title: \(title) \nBody:\(body)")

    
    
}