如何使用Firebase读取推送通知中发送的自定义数据

时间:2018-07-24 12:13:30

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

我正在尝试检索在iOS应用程序(Swift)中使用Firebase在推送通知中发送的“数据”

这是我用来发送通知的代码:

{
   "to": "dWB537Nz1GA:APA91bHIjJ5....",
   "data":
   {
      "message": "Offer!",
      "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
   },
   "notification":
   {
      "body": "Enter your message",
      "sound": "default"
   }
}

我仅实现了一种从通知中读取数据的方法:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    //checked where I can get custom data which I sent but no success
    let notification =  response.notification.request.content.body

    print("Notification recived content:\(response.notification.request.content)")
    print("userNotificationCenter : didReceive response body : \(notification)")
    print("userNotificationCenter : didReceive response user info : \(response.notification.request.content.userInfo)")
    print("userNotificationCenter : response : \(response)")


    completionHandler()
}

通过上述方法签入,我可以获取发送的自定义数据,但没有成功

我在很多地方都在寻找解决方案,但没有成功。请帮助我检索自定义数据。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我正在像这样迅速地使用

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


    if let menu = userInfo["Menu"] as? NSString {
        print(menu)
    }

    Messaging.messaging().appDidReceiveMessage(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}

这是我用来发送通知的代码:

{
   "to": "/topics/....",
   "data":
   {
      "Menu": "Summary"
   },
   "notification":
   {
      "title": "Header",
      "text": "Message",
      "sound": "default"
   }
}