无法访问gcm数据响应

时间:2018-09-18 06:31:52

标签: ios swift firebase google-cloud-messaging firebase-cloud-messaging

如何访问(“ gcm.notification.data”)值? 我可以使用以下代码访问(“ aps”)值:

    if let aps = userInfo["aps"] as? NSDictionary {
                if let alert = aps["alert"] as? NSDictionary {
                    if let title = alert["title"] as? NSString,let body = alert["body"] as? NSString{
print(title)
print(body)
}

消息响应

    [AnyHashable("gcm.notification.data"): {"status":"7809","body":"sgjh body"}, 
AnyHashable("aps"): {
    alert =     {
        body = "sgjh body";
        title = "yfguhj title";
    };
    badge = 1;
    "content-available" = 1;
    sound = default;
}]

3 个答案:

答案 0 :(得分:0)

if let gcmData = userInfo["gcm.notification.data"] as? NSDictionary {

    for (key, value) in gcmData {

        guard let key = key as? String else { continue }

        switch (key, value) {
        case ("status", let aValue as Double): print(aValue)
        case ("body", let aValue as String): print(aValue)
        default: continue
        }
    }
}

答案 1 :(得分:0)

使用委托UNUserNotificationCenterDelegate,当您收到通知并尝试以下代码时,将触发该委托:

 func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
     if let notificationString = userInfo?["gcm.notification.data"] as? String {
     print(notificationString)
    let data = notificationString.data(using: .utf8)!
    do {
         if let jsonDictionary = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String: Any]
        {
           print (jsonDictionary["body"])
        } else {
         print("bad json")
        }
     } catch let error as NSError {
      print(error)
      }
    }

 }

答案 2 :(得分:0)

在Swift中停止使用NSDictionaryNSString。已经将userInfo转换为原生Swift类型

gcm.notification.dataaps处于同一级别

guard let userInfo = userInfo as? [String:Any] else { return } 

if let gcmData = userInfo["gcm.notification.data"] as? [String:Any] {
   print(gcmData["status"] as! String, gcmData["body"] as! String)
}
if let aps = userInfo["aps"] as? [String:Any] { ...