I am developing an iOS application that should receive push notifications sent from the Firebase console. I am using Swift 3 and iOS 10.
As recommended in the Firebase documentation, we must assign our delegate object UNUserNotificationCenterto an object to receive and display notifications and an object FIRMessagingto receive data messages before our application finishes launching.
This was done in a method didFinishLaunchingWithOptions. I followed all the steps to configure Firmessaging as well as APN.
Now, when I send a message from the Firebase console, I get it using the method applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage).
The problem is that I could not extract the message body from the dictionary remoteMessage.appData. Knowing that the body is within remoteMessage.appData["notification"]. Indeed, the instruction
print(remoteMessage.appData)
prints
[AnyHashable("notification"): {
body = Hello Notifications;
e = 1;
}, AnyHashable("from"): 49679924394, AnyHashable("collapse_key"): com.company.app]
Print
remoteMessage.appData["notification"]
shows
{
body = Hello Notifications;
e = 1;
}
I tried
remoteMessage.appData["notification"]["body"]
and
remoteMessage.appData["notification"].body
but this leads to a syntax error. I could not remove the body to show it in the controller. The appDelegate code is below.
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()
UNUserNotificationCenter.current().delegate = self
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
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)
}