从Apple推送通知中解析数据

时间:2018-04-15 17:15:04

标签: json swift apple-push-notifications firebase-cloud-messaging

我有通过Firebase发送的推送通知,当用户执行操作时,有一个php脚本发送推送到关联的FCM令牌。正在接收推送通知,但我正在尝试从" gcm.notification.payload"中获取信息。键。我已经尝试将userInfo转换为Dictionary,NSDictionary,[String:Any],JSON,并且没有任何工作。当我试着说,有效载荷[" type"]。字符串时,值为nil。这是我能够从有效负载字典中获取内容的最接近的地方,其中通知是收到的UNNotification:

let userInfo = notification.request.content.userInfo


let json = JSON(notification.request.content.userInfo)
guard let gcmNotificationPayload = json["gcm.notification.payload"].string else { return }
let payload = JSON(gcmNotificationPayload)
print("json \(json)")
print("payload \(payload)")
print("\(notification.request.content.userInfo)")

控制台输出:

  json {
      "gcm.message_id" : "0:1523811750249807%3990eb5d3990eb5d",
      "aps" : {
        "sound" : "default",
        "badge" : 1,
        "alert" : {
          "body" : "Tap to Open Herds List",
          "title" : "test4 test has added you to a herd!"
        }
      },
      "gcm.notification.payload" : "{\"image\":\"https:\\\/\\\/www.test.com\\\/images\\\/users\\\/417\\\/5acd085c97c3a.jpg\",\"type\":\"6\",\"title\":\"test4 test has added you to a herd!\",\"message\":\"Tap to Open Herds List\"}"
    }

    payload {"image":"https:\/\/www.test.com\/images\/users\/417\/5acd085c97c3a.jpg","type":"6","title":"test4 test has added you to a herd!","message":"Tap to Open Herds List"}

    [AnyHashable("gcm.message_id"): 0:1523811750249807%3990eb5d3990eb5d, AnyHashable("aps"): {
        alert =     {
            body = "Tap to Open Herds List";
            title = "test4 test has added you to a herd!";
        };
        badge = 1;
        sound = default;
    }, AnyHashable("gcm.notification.payload"): {"image":"https:\/\/www.test.com\/images\/users\/417\/5acd085c97c3a.jpg","type":"6","title":"test4 test has added you to a herd!","message":"Tap to Open Herds List"}]

1 个答案:

答案 0 :(得分:2)

将let有效负载行更改为此解决了问题,这是使用SwiftyJSON进行记录:

let payload = JSON.init(parseJSON: gcmNotificationPayload)