iOS:无法解析来自 firebase 的推送通知

Posted

技术标签:

【中文标题】iOS:无法解析来自 firebase 的推送通知【英文标题】:iOS: Unable to parse push notification from firebase 【发布时间】:2018-10-02 11:48:21 【问题描述】:

我是 ios 新手,目前正在开发一款约会应用。我已经在 android 中实现了firebase push,它工作正常,但是当通知在 iOS 设备上出现时,它以原始json 格式出现。

通过搜索,我了解到 iOS 为推送通知提供了固定格式,例如:

 
  "aps": 
         "alert":"Testing.. (0)",
         "badge":1,
         "sound":"default",
         "mutable-content": 1,
         "attachment-url": ""
         

但我的json 数据以其他格式出现,我无法解析它以显示正确的通知。

My Format


 "aps" : 
         "badge" : 50,
         "alert" : 
                    "body" : "\"notificationId\":\"Flootapp\",\"DateMatchHistoryId\":\"BJgV-_PYX\",\"id\":\"Syn-XlnHX\",\"message\":\"Congratulations! You have a match with Rishi Raj. Confirm quickly\",\"type\":\"matched\"",
                    "title" : "Floot"
                   
          ,
 "gcm.message_id" : "0:1537863976816788%835a2461835a2461",
 "message" : "\"notificationId\":\"Flootapp\",\"DateMatchHistoryId\":\"BJgV-_PYX\",\"id\":\"Syn-XlnHX\",\"message\":\"Congratulations! You have a match with Rishi Raj. Confirm quickly\",\"type\":\"matched\"",
 "badge" : "50",
 "messageFrom" : "Floot",
 "alert" : "\"notificationId\":\"Flootapp\",\"DateMatchHistoryId\":\"BJgV-_PYX\",\"id\":\"Syn-XlnHX\",\"message\":\"Congratulations! You have a match with Rishi Raj. Confirm quickly\",\"type\":\"matched\"",
 "google.c.a.e" : "1"

 

我在这里缺少的任何东西。请帮忙。 提前致谢!

【问题讨论】:

能否提供您的 JSON 数据格式? "我的 json 数据以其他格式出现" 还有什么其他格式? @StacySmith 更新了我的格式。 @Larme 更新了我的格式。请看一看。 JSON 中有 JSON。你需要拨打JSONSerialization就可以了。 【参考方案1】:

希望这会对您有所帮助。在 appdelegate 中使用它:

     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) 
            print(userInfo)
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary
            print(aps!)
            let alert = aps!["alert"] as? NSDictionary
            print(alert!)
            let body = let body = alert![AnyHashable("body")] as? String
            let title = alert!["title"] as? String
            print(title!)
            print(body!)

           let jsonData = body?.data(using: .utf8)!

           let json = try! JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) as! NSDictionary
           print(json)
           let notificationId = json["notificationId"] as! String
    

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

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: true)
        let content = UNMutableNotificationContent()
        content.title = "YourAppName"
        content.body = userInfo.description
        let request = UNNotificationRequest(identifier: "YourAppName", content: content, trigger: trigger)

        let currentBadgeNumber = UIApplication.shared.applicationIconBadgeNumber
        let updatedBadgeNumber = currentBadgeNumber + 1
        if (updatedBadgeNumber > -1)  UIApplication.shared.applicationIconBadgeNumber = updatedBadgeNumber 

        UNUserNotificationCenter.current().add(request) (error) in
        
    

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

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
        let content = UNMutableNotificationContent()
        content.title = "YourAppName"

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let _ = alert["body"] as? String,
            let _ = alert["title"] as? String
            else 
                return
        
        content.title = (alert["title"] as? String)!
        content.body = (alert["body"] as? String)!

        notificationText = ""

        let request = UNNotificationRequest(identifier: "YourAppName", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) (error) in
        
        self.backGround = "true"

    

【讨论】:

请不要在 Swift 中使用 NSDictionary(或 NSStuff),如果有等价的。此外,这是一个很大的力量展开。有些没有意义:let alert = aps!["alert"] as? NSDictionary 后跟 print(alert!) @MaheshShahane 推送在我执行此操作后停止接收。 我不想打印,我想显示通知。【参考方案2】:

我认为这会对您有所帮助。 首先,您需要从推送通知响应中查找用户信息。

您需要在此“YourKey”中设置要访问的密钥。你会得到[String: Any] 类型的对象。之后,您可以从 dict 对象访问您的值。

如果您获取message 数据,则需要设置message 代替YourKey

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) 
            let info = response.notification.request.content.userInfo
            if let notiStr = info["YourKey"] as? String, let dict = self.convertToDictionary(text: notiStr) 
                  print(items: dict)
            
            return completionHandler()



func convertToJson(text: String) -> [String: Any]? 
        if let data = text.data(using: .utf8) 
            do 
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
             catch 
                print(error.localizedDescription)
            
        
        return nil

【讨论】:

这个方法没有被调用,而是 public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) 它被调用.

以上是关于iOS:无法解析来自 firebase 的推送通知的主要内容,如果未能解决你的问题,请参考以下文章

iOS 13 及更高版本未收到来自 Firebase 的推送通知

收到来自 Firebase 的推送通知 ios 但没有声音或在通知中心

解析到 Firebase 增强的推送通知

无法使用java在IOS中发送firebase推送通知

iOS 中的推送通知突然无法通过 Firebase 传递

没有收到来自 Firebase 控制台的推送通知