0

I am testing my code to see how UserNotifications works, and I have this code that should show three buttons, and it shows the notification but it doesn't show any of the buttons. What am I doing wrong?

I followed the instructions at

https://developer.apple.com/documentation/usernotifications/scheduling_a_notification_locally_from_your_app

https://developer.apple.com/documentation/usernotifications/declaring_your_actionable_notification_types

This code is in the view controller class of my iOS project.

let center = UNUserNotificationCenter.current()  

var categories = Set<UNNotificationCategory>()  

override func viewDidLoad() {  
    super.viewDidLoad()  

    center.requestAuthorization(options: [.alert, .badge, .carPlay, .sound]) {  

        (granted, error) in  

        guard error == nil else {  

            print(error!.localizedDescription)  

            return  

        }  

        guard granted else {  

            print("granted=", granted)  

            return  

        }  

        print("!!!")  

    }  

    let actionOK = UNNotificationAction(identifier: "HELLO_OK", title: "OK", options: UNNotificationActionOptions(rawValue: 0))  

    let actionTwo = UNNotificationAction(identifier: "TWO", title: "Two", options: UNNotificationActionOptions(rawValue: 0))  

    let actionThree = UNNotificationAction(identifier: "THREE", title: "Three", options: UNNotificationActionOptions(rawValue: 0))  

    let categoryGreeting = UNNotificationCategory(identifier: "HELLO", actions: [actionOK, actionTwo, actionThree], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "", options: .customDismissAction)  

    categories.insert(categoryGreeting)  

    center.setNotificationCategories(categories)  

    let content = UNMutableNotificationContent()  
    content.title = "Hello World!"  
    content.body = "May the Force be with you."  

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (10), repeats: false)  

    // Create the request  
    let uuidString = UUID().uuidString  
    let request = UNNotificationRequest(identifier: uuidString,  
                                        content: content, trigger: trigger)  

    // Schedule the request with the system.  
    center.add(request) { (error) in  
        if error != nil {  
            // Handle any errors.  
        }  
    }  

}  

I looked at older questions at stackoverflow, but they applied to older versions of iOS and they didn't help me.

daniel
  • 1,446
  • 3
  • 29
  • 65

1 Answers1

0

It was a simple mistake. I had not set the categoryIdentifier of the UNMutableNotificationContent object. The solution is to set it to "HELLO".

daniel
  • 1,446
  • 3
  • 29
  • 65