我正在开发一个iOS应用,该应用应接收从Firebase控制台发送的推送通知。我正在使用Swift 3和iOS 10。
根据Firebase文档的建议,我们必须在应用程序启动完成之前,将委托对象分配给UNUserNotificationCenter
对象以接收和显示通知,并分配FIRMessaging
对象以接收数据消息。
这已通过didFinishLaunchingWithOptions
方法完成。我按照所有步骤进行操作,以配置固件消息传递和APN。
现在,当我从Firebase控制台发送消息时,我通过applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage)
方法收到了消息。
问题是我无法从remoteMessage.appData
字典中提取消息的正文。知道主体在remoteMessage.appData["notification"]
内。确实,指令
print(remoteMessage.appData)
版画
[AnyHashable("notification"): {
body = Hello Notifications;
e = 1;
}, AnyHashable("from"): 49679924394, AnyHashable("collapse_key"): com.company.app]
列印
remoteMessage.appData["notification"]
表演
{
body = Hello Notifications;
e = 1;
}
我试过了
remoteMessage.appData["notification"]["body"]
和
remoteMessage.appData["notification"].body
但这会导致语法错误。我无法提取主体以将其显示在警报控制器中。 appDelegate的代码如下。
class AppDelegate: UIResponder, UIApplicationDelegate, FIRMessagingDelegate, UNUserNotificationCenterDelegate{
......
func application(_ application: UIApplication, didFinishLaunchingWithOptions, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
application.isStatusBarHidden = true
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: authOptions, completionHandler: {_ ,_ in })
application.registerForRemoteNotifications()
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
print(remoteMessage.appData["notification"]!)
let alertController = UIAlertController(title: "Message from IOBird Developer Team", message: "?????? Body of the message ?????", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alertController.addAction(OKAction)
self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
}
最佳答案
感谢Arthur Thompson的帮助,您给了我这个主意。如果有人需要,我会发布答案。我写
let d : [String : Any] = remoteMessage.appData["notification"] as! [String : Any]
let body : String = d["body"] as! String
print(body)