1

我有一个应用程序。它使用FCM推送通知。消息的JSON看起来象:iOS Firebase云消息传递在应用关闭时获取数据

{ "to": "xxx", "notification" : { 
      "body" : "Hi", 
      "badge" : 1, 
      "sound" : "default" 
     }, 
     "data" :  { 
      "id" : "xxx", 
      "first_name" : "xxx", 
      "last_name" : "xxx", 
      "full_name" : "xxx", 
      "primary_image" : "xxx", 
      "matchid" : "xxx", 
      "type": "match"/"message" 
     }, 
     "content_available": true, 
     "priority": "high" 
} 

我有数据的“类型”,以检测屏幕上会发动时摸我的通知。如果键入==“匹配” - >转到MatchVC,并键入==“消息” - >转到MessageVC。我有一个问题,如果我的应用程序在前台,我可以从didReceiveRemoteNotification:userinfo达到数据,然后我可以检测到推动屏幕,但是如果我的应用程序是背景或关闭,我只收到没有来自didReceiveRemoteNotification:userinfo的数据的通知。当我点击通知时,它只是打开我的应用程序。任何解决方案,赞赏。

回答

0

在Firebase iOS sdk中,您应该在应用程序委托中包含以下代码段。

注意有2个userNotificationCenter方法。当应用程序是前台时,第一个会被调用。当您点击纸盘中的推送通知时,第二位会被呼叫。

完整的代码可以从Firebase Official Github存储库(iOS快速入门)中找到。 https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExampleSwift/AppDelegate.swift

@available(iOS 10, *) 
extension AppDelegate : UNUserNotificationCenterDelegate { 

    // 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("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print("userInfo 1st") 
     print(userInfo) 

     let id = userInfo["id"] 
     let firstName = userInfo["first_name"] 

     print(id ?? "") 
     print(firstName ?? "") 

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

    func userNotificationCenter(_ center: UNUserNotificationCenter, 
           didReceive response: UNNotificationResponse, 
           withCompletionHandler completionHandler: @escaping() -> Void) { 
     let userInfo = response.notification.request.content.userInfo 
     // Print message ID. 
     if let messageID = userInfo[gcmMessageIDKey] { 
      print("Message ID: \(messageID)") 
     } 

     // Print full message. 
     print("userInfo 2nd") 
     print(userInfo) 

     let id = userInfo["id"] 
     let firstName = userInfo["first_name"] 

     print(id ?? "") 
     print(firstName ?? "") 

     completionHandler() 
    } 
} 
相关问题