iOS 如何从 Firebase FCM 推送通知获取数据

How to get data from Firebase FCM push notification in iOS

我正在发送推送通知至:

https://fcm.googleapis.com/fcm/send

格式为(在 php 中):

   [
      'to' => $token,
      'data' => [
         'key' => $val
      ],
      'notification' => [
         'title' => $title,
         'body' => $message,
         'badge' => $badge,
         'sound' => 'default'
      ]
   ]

我的 iOS 应用程序完美地接收和显示推送,包括前景和背景。但是我找不到如何访问 data

在我的 AppDelegate 文件中我有:

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

   let aps = userInfo[AnyHashable("aps")] as! JsonObject
   print(aps)
}

并且 print 语句的调试显示:

["sound": default, "badge": 1, "alert": {
    body = "One flew over the cuckoo's nest";
    title = "My Title";
}]

那我的data: {key:val}呢??

数据应该可以直接在 userInfo 字典中找到,而不是在“aps”键上,您应该可以像这样访问它:

let customValue = userInfo["customKey"] as? String

如 Firebase 所述documentation

The payload of notification messages is a dictionary of keys and values. Notification messages sent through APNs follow the APNs payload format as below:

{
    "aps" : {
      "alert" : {
        "body" : "great match!",
        "title" : "Portugal vs. Denmark",
      },
      "badge" : 1,
    },
    "customKey" : "customValue"
  }