iOS Push Notification Action is not showing up
Asked Answered
N

2

10

My app has a connection to the Firebase-server, also to send Push Notifications. Now, I want to go a step further and add an action to the notifications. After going throw lots of tutorials, it´s still not working for me. The action-button is not showing up, as you can see here:

enter image description here

Here is my code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.applicationIconBadgeNumber = 0
    FirebaseApp.configure()
    registerForPushNotifications()
    return true
}

func registerForPushNotifications() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        (granted, error) in
        print("Permission granted: \(granted)")

        guard granted else { return }

        let viewAction = UNNotificationAction(identifier: "addToCal",
                                              title: "Zum Kalender hinzufügen",
                                              options: [.foreground])

        let newsCategory = UNNotificationCategory(identifier: "NEW_SESSION",
                                                  actions: [viewAction],
                                                  intentIdentifiers: [],
                                                  options: [])
        UNUserNotificationCenter.current().setNotificationCategories([newsCategory])
        self.getNotificationSettings()
    }
}

func getNotificationSettings() {
    UNUserNotificationCenter.current().getNotificationSettings { (settings) in
        print("Notification settings: \(settings)")
        guard settings.authorizationStatus == .authorized else { return }
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

As I saw at this tutorial, I also added the "category" key with the value "NEW_SESSION" to the push notification I´m sending, but it´s not working as well.enter image description here

Update: I noticed that the "category" key is passed through the notification, so its just a question to handle it right. The userInfo Dictionary looks like this:

{ "aps" : { 
"alert" : { 
"body" : "This notification has no action", 
"title" : "Test", 
} 
}, 
"category" : "NEW_SESSION" 
} 
Norfolk answered 11/7, 2017 at 20:14 Comment(15)
I'm not sure. From your viewAction: try changing from [.foreground] to []Individuality
Nope, nothing has changed:( Thanks for your answer dude:)Norfolk
FYI when you receive the notification, it will look the same. To see the actions you must tap and drag the notification down. Did you do that?Individuality
Yes, of course. You can see it in the picture above:DNorfolk
I did see the image. Not sure if I communicated well. After seeing the notification on your screen: Did you tap and drag the notification down?!Individuality
Yes of course :DNorfolk
Let us continue this discussion in chat.Individuality
@Honey, Now I implemented a function that displays the userInfo in an alertView. It looks like this. It should also display the category String I set, shouldn't´t? But it´s not doing.Norfolk
Delete the app.( dont reinstall. Delete it and then install again) and see if it works. If that doesn't work then also do a clean build using cmmd k and also do cmmd + shift + k. But I have a reason to believe deleting it and installing it again could solve your problemIndividuality
My point is make sure after you delete and install the app...the app shows you the alert of "allow notifications" / "dont allow notifications".Individuality
Also in case you haven't noticed you misspelled category. You wrote it as 'catogary'Individuality
@Honey, Jup the alert to allow/not allow was poping up. And no, nothing has changed:( At the [firebase doc] (firebase.google.com/docs/cloud-messaging/…) I noticed that you have to use "click_action" instead of "category". But this hasn't changed anything, and that's why I've contacted the firebase support now. Thank you for your support:)Norfolk
See here and here. You have to accomplish that through an API call.Individuality
@Honey, I don´t understand where I have to type in the HTTP messages:/Norfolk
I don't know where you have to write that request. Ask that on the linked answers.Individuality
P
9

The buttons do not appear on their own. On supported devices you have to 3D touch the notifications to show the content or buttons. On non-supported devices you can try swiping down or left/right for the buttons to show.

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            print("Permission granted: \(granted)")

            guard granted else { return }

            let action = UNNotificationAction(identifier: "addToCal", title: "Zum Kalender hinzufügen", options: [])
            let category = UNNotificationCategory(identifier: "NEW_SESSION", actions: [action], intentIdentifiers: [], options: [])
            UNUserNotificationCenter.current().setNotificationCategories([category])

            self.getNotificationSettings()
        }

And add UNUserNotificationCenterDelegate methods to handle action.

@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) {
        // Print message ID.
        // Print full message.
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.actionIdentifier == "addToCal" {

            //Handel action.
        }
    }
}

And don't forgot to set delegate as:

UNUserNotificationCenter.current().delegate = self

Payload format

{
    "aps" : {
              "category" : "NEW_MESSAGE_CATEGORY",
               "alert" : {
                        "body" : "Acme message received from Johnny Appleseed",
                        "title" : "Test",
                    },
               "badge" : 3,
             },
}
Plowshare answered 12/7, 2017 at 11:43 Comment(5)
In the tutorial i links above, the payload looks like this: { "aps": { "alert": "Breaking News!", "sound": "default", "link_url": "https://raywenderlich.com", "category": "NEWS_CATEGORY" } } and mine is { "aps" : { "alert" : { "body" : "This notification has no action", "title" : "Test", } }, "catogary" : "NEW_SESSION" }. As you can see, in the working payload "category" is placed in "aps" and mine not. I'm pretty sure that the error/bug is caused by this.Norfolk
@Norfolk Please match the payload format as my updated answer or you can follow developer.apple.com/library/content/documentation/…Plowshare
@NikhleshBagdiya I cannot change the order in the payload. I've contacted the firebase support now.Norfolk
@Norfolk for actionable firebase notification you can follow #39138227Plowshare
The fact that the buttons don't show up automatically unless the user performs a 3D touch on the notification was an important piece of information that I was missing! Thanks for mentioning it.Concord
J
2

For me it works when I have the "category" included in "aps" dictionary and it does not work when I have it outside of "aps". And also, did you guys noticed that in the payload that Devhess posted as an update to his question the "category" field is misspelled. So instead of "category" we have "catogary" there. This also could be the problem. This payload works for me:

{ "aps":{ "alert":{ "body":"This notification has ACTIONS", "title":"ACTIONABLE Notification title" }, "badge":1, "sound":"default", "category":"NEW_SESSION" } }

Janson answered 18/7, 2018 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.