swift : Show the content of push notification in UIAlertView

1.5k Views Asked by At

How can I show the contents of a push notificantion (FCM) in UIAlertView in swift?

This link was not helpful because it is for ObjectiveC...

I want when a push notification (FCM) is received to display a UIAlertView to the client with specific message. For example:

If ("a" received from FCM) display "specific message 1 in UIAlertView", else if ("b" received from FCM) display "specific message 2 in UIAlertView".

I just tried this, but it is not working out for me:

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


        // display alert view when notification is received !!!
        let alertController = UIAlertController(title: "Alert", message: "you have a new notification", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "No", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.window?.rootViewController?.present(alertController, animated: true, completion: nil)

}
1

There are 1 best solutions below

0
On

Are you getting any errors in your console when you try to present the alert? Sometimes when when presenting things from AppDelegate I see something like this:

2017-01-01 16:04:14.806 wylt[46457:5781064] Warning: Attempt to present <UIAlertController: 0x7faf13f0a910> on <wylt.WYLTNavigationViewController: 0x7faf1402e200> whose view is not in the window hierarchy!

I prefer to find the top view controller and present the alert from there instead... but putting the call to present inside an async block also worked for me.

DispatchQueue.main.async {
    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
}