iOS: не удается разобрать push-уведомление из firebase - PullRequest
0 голосов
/ 02 октября 2018

Я новичок в iOS и в настоящее время работаю над приложением для знакомств.Я уже внедрил firebase push в Android, и он работает нормально, но когда уведомление приходит на устройстве iOS, оно приходит в формате json.

При поиске я узнал, что iOS предоставляет исправленныеформат для push-уведомлений, например:

{ 
  "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"

 }

Все, что мне здесь не хватает.Пожалуйста помоги.Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 02 октября 2018

Пусть это вам поможет.используйте это в 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"

    }
0 голосов
/ 02 октября 2018

Я думаю, это поможет вам.Сначала вам нужно найти информацию о пользователе в ответе на push-уведомление.

Вам необходимо установить ключ, к которому вы хотите получить доступ в этом "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
}
...