Search code examples
apple-push-notificationswatchkit

Add buttons to dynamic notification interface


I'm creating a custom dynamic notification to show the user. Once i receive this notification at didReceiveNotification function at NotificationController I set the interface outlets with the right data. My problem is that i did not realize how can i add a custom button above the default dismiss button, since the notification storyboard doesnt allow buttons insertion and Apple Documentation says that

Do not include buttons, switches, or other interactive controls.

But i saw a lot of watch applications that have their custom actions, as Messages and Facebook Messenger. There is any way to add custom actions to the dynamic interface at watchOS?


Solution

  • You simply cannot add buttons to Dynamic notification interfaces. If you try to do this, you will receive the error

    Illegal Configuration: Buttons are not supported in Notification interfaces.

    However, you can add system buttons to your notifications other than the Dismiss button. When setting up the categories for the notification center, you can specify custom UNNotificationActions to be added to your notification category.

    var categories = Set<UNNotificationCategory>()
    let myCategory = UNNotificationCategory(identifier: "MyCategory", actions: [/*your custom actions go here*/], intentIdentifiers: [], options: []) //set up the actions here
    categories.insert(myCategory)
    center.setNotificationCategories(categories)
    

    Then you can handle the user interactions with these actions (which as displayed as normal buttons on your dynamic notification interface) in your the UNUserNotificationCenterDelegate method, userNotificationCenter(_:didReceive:withCompletionHandler:) like this:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        switch response.actionIdentifier {
        case "Ok":
            print("Ok action tapped")
        case "Dismiss":
            print("Dismiss action tapped")
        default:
            break
        }
        completionHandler()
    }