Google Firebase消息传递 - 在Swift 3中解析推送通知

问题描述:

我一直在使用Google Firebase消息传递系统(成功)进行游戏。我可以将消息发送到我的iPhone,并订阅/取消订阅群组/主题,现在我想管理和处理推送通知,当他们到达电话。Google Firebase消息传递 - 在Swift 3中解析推送通知

// Receive displayed notifications for iOS 10 devices. 
func userNotificationCenter(_ center: UNUserNotificationCenter, 
          willPresent notification: UNNotification, 
          withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    let userInfo = notification.request.content.userInfo 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("1 Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 

    // Change this to your preferred presentation option 
    completionHandler([]) 
} 

这是谷歌的默认代码,当一个推送通知到达时,应用程序看到并打印我正常工作:


    1 Message ID: 0:1007%4xxxxxxxxxa 
    [AnyHashable("gcm.message_id"): 0:1007%4xxxxxa, AnyHashable("aps"): { 
     alert =  { 
      body = "Breaking News: "; 
      title = "The latest update"; 
     }; 
     category = "http://amp.sportsmole.co.uk/football/"; 
    }] 

然而,当我尝试使用各种斯威夫特3个JSON处理工具我结束了错误。

例如,如果我尝试:

let data = userInfo[gcmMessageIDKey] 
    let json = try? JSONSerialization.jsonObject(with: data, options: []) 

我得到一个错误,与参数类型的JSONObject是不是我需要的。

任何见解?

+0

经过一番玩这似乎工作: –

经过一番玩这个似乎工作:

// Print full message. 
    print("%@", userInfo) 
    var body = "" 
    var title = "" 
    var msgURL = "" 
    print("==============") 

    guard let aps = userInfo["aps"] as? [String : AnyObject] else { 
     print("Error parsing aps") 
     return 
    } 
    print(aps) 

    if let alert = aps["alert"] as? String { 
     body = alert 
    } else if let alert = aps["alert"] as? [String : String] { 
     body = alert["body"]! 
     title = alert["title"]! 
    } 

    if let alert1 = aps["category"] as? String { 
     msgURL = alert1 
    } 

    print(body) 
    print(title) 
    print(msgURL) 

    // 

不知道这是太明显了,我早该知道,或者如果它只是不是东西,是有据可查的。