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" 
} 
Nike Kov
  • 12,630
  • 8
  • 75
  • 122
Devhess
  • 289
  • 4
  • 16
  • I'm not sure. From your viewAction: try changing **from** `[.foreground]` to `[]` – mfaani Jul 11 '17 at 20:37
  • Nope, nothing has changed:( Thanks for your answer dude:) – Devhess Jul 11 '17 at 20:44
  • 1
    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? – mfaani Jul 11 '17 at 20:49
  • Yes, of course. You can see it in the picture above:D – Devhess Jul 11 '17 at 20:51
  • 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?! – mfaani Jul 11 '17 at 20:53
  • Yes of course :D – Devhess Jul 11 '17 at 20:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148940/discussion-between-honey-and-devhess). – mfaani Jul 11 '17 at 21:00
  • @Honey, Now I implemented a function that displays the userInfo in an alertView. It looks like [this](http://imgur.com/xIILjRx). It should also display the category String I set, shouldn't´t? But it´s not doing. – Devhess Jul 11 '17 at 21:03
  • 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 problem – mfaani Jul 12 '17 at 13:14
  • My point is make sure after you delete and install the app...the app shows you the alert of "allow notifications" / "dont allow notifications". – mfaani Jul 12 '17 at 13:25
  • Also in case you haven't noticed you misspelled category. You wrote it as 'catogary' – mfaani Jul 12 '17 at 14:11
  • 2
    @Honey, Jup the alert to allow/not allow was poping up. And no, nothing has changed:( At the [firebase doc] (https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support) 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:) – Devhess Jul 12 '17 at 14:27
  • 1
    See [here](https://stackoverflow.com/questions/39137727/how-to-send-actionable-notifications-to-ios-with-firebase) and [here](https://stackoverflow.com/questions/42297505/firebase-cloud-messaging-click-action-format-is-platform-specific). You have to accomplish that through an API call. – mfaani Jul 12 '17 at 14:48
  • @Honey, I don´t understand where I have to type in the HTTP messages:/ – Devhess Jul 13 '17 at 09:58
  • I don't know where you have to write that request. Ask that on the linked answers. – mfaani Jul 13 '17 at 19:29

2 Answers2

8

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,
             },
}
Nike Kov
  • 12,630
  • 8
  • 75
  • 122
Nikhlesh Bagdiya
  • 4,316
  • 1
  • 19
  • 29
  • 1
    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. – Devhess Jul 12 '17 at 12:12
  • @Devhess Please match the payload format as my updated answer or you can follow https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html – Nikhlesh Bagdiya Jul 12 '17 at 12:26
  • @NikhleshBagdiya I cannot change the order in the payload. I've contacted the firebase support now. – Devhess Jul 12 '17 at 14:28
  • 2
    @Devhess for actionable firebase notification you can follow https://stackoverflow.com/questions/39137727/how-to-send-actionable-notifications-to-ios-with-firebase – Nikhlesh Bagdiya Jul 12 '17 at 14:59
  • 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. – bmt22033 Jul 27 '18 at 14:53
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" } }

Gritco Ion
  • 21
  • 1