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



我是推送通知的新手,我设法让推送通知工作。现在,每当推送通知出现时,如果我按下它,该应用程序将打开并进入一个页面。

这是我的推送通知消息

{"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)
}

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

(对不起,如果这听起来很傻,但这是我第一次尝试这样做,我尝试环顾四周,但找不到任何正确的答案(

只需使用以下代码即可进行工作测试

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)
}
}
}

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)")


}

相关内容

  • 没有找到相关文章

最新更新