iosswiftunusernotification

Actionable notifications not showing actions Swift 4


I'm learning the new notification system but I'm having trouble with actions. The notification works, but I do't get an action with it. I'm following a tutorial on https://www.appcoda.com/ios10-user-notifications-guide/ but I don't seem to get actions to appear with notification.

As you can see the commented out part in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil)is where I cannot seem to get where it goes, can anyone see where I'm mistaking?

import UIKit
import UserNotifications

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func scheduleNotification(at date: Date) {
        UNUserNotificationCenter.current().delegate = self

        //compone a new Date components because components directly from Date don't work
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: date)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
        //create the trigger with above new date components, with no repetitions
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

        //create the content for the notification
        let content = UNMutableNotificationContent()
        content.title = "Tutorial Reminder"
        content.body = "Just a reminder to read your tutorial over at appcoda.com!"
        content.sound = UNNotificationSound.default()
        // notification action category


        //add an image to notification
          //convert logo to url
        if let path = Bundle.main.path(forResource: "logo", ofType: "png") {
            let url = URL(fileURLWithPath: path)


            do {     // because UNNotificationAttachment is mark as throwing we need an attach block for handling errors
                let attachment = try UNNotificationAttachment(identifier: "logo", url: url, options: nil)
                content.attachments = [attachment]
                content.categoryIdentifier = "myCategory"
            } catch {
                print("The attachment was not loaded.")
            }
        }


        //create the request for notification with desired parameters
        let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

        //add the request to notification center after removing all notifications
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print("Uh oh! We had an error: \(error)")
            }
        }


    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
//        let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
//        let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
//        UNUserNotificationCenter.current().setNotificationCategories([category])

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in
            if !accepted {
//                print("Notification access denied.")
//                let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
//                let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
//                UNUserNotificationCenter.current().setNotificationCategories([category])
            }
        }
        let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: [])
        let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: [])
        UNUserNotificationCenter.current().setNotificationCategories([category])


        return true
    }

}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    if response.actionIdentifier == "remindLater" {
        let newDate = Date(timeInterval: 5, since: Date())
        scheduleNotification(at: newDate)
    }

//    UNUserNotificationCenter.current().delegate = self

   }
}

EDIT:

after @VIP-DEV answer I changed the code, to add the reminder in it's own action, into:

import UIKit
import UserNotifications

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate

        configureCategory()
        triggerNotification(at: Date())
        requestAuth()

        return true
    }


    private let category = "Notification.Category.Read"

    private let readActionIdentifier = "Read"
    private let waitActionIdentifier = "Wait"

    private func requestAuth() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
            if let error = error {
                print("Request Authorization Failed (\(error), \(error.localizedDescription))")
            }
        }
    }

    func triggerNotification(at date: Date) {
        // Create Notification Content
        let notificationContent = UNMutableNotificationContent()

        //compone a new Date components because components directly from Date don't work
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: date)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)
        //create the trigger with above new date components, with no repetitions





        // Configure Notification Content
        notificationContent.title = "Hello"
        notificationContent.body = "Kindly read this message."

        // Set Category Identifier
        notificationContent.categoryIdentifier = category

        // Add Trigger
//        let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
//        // Create Notification Request
        let notificationRequest = UNNotificationRequest(identifier: "test_local_notification", content: notificationContent, trigger: trigger)
//
        // Add Request to User Notification Center
        UNUserNotificationCenter.current().add(notificationRequest) { (error) in
            if let error = error {
                print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
            }
        }
    }

    private func configureCategory() {
        // Define Actions
        let read = UNNotificationAction(identifier: readActionIdentifier, title: "Read", options: [])
        let wait = UNNotificationAction(identifier: waitActionIdentifier, title : "Wait", options: [])
        // Define Category
        let readCategory = UNNotificationCategory(identifier: category, actions: [read, wait], intentIdentifiers: [], options: [])

        // Register Category
        UNUserNotificationCenter.current().setNotificationCategories([readCategory])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        switch response.actionIdentifier {
        case readActionIdentifier:
            print("Read tapped")
        case waitActionIdentifier:
            let NewDate = Date(timeInterval: 20, since: Date())
            triggerNotification(at: NewDate)
            print("Wait tapped")
        default:
            print("Other Action")
        }

        completionHandler()
    }


}

and

class ViewController: UIViewController {
    @IBAction func datePickerDidSelectNewDate(_ sender: UIDatePicker) {

        let selectedDate = sender.date
        let delegate = UIApplication.shared.delegate as? AppDelegate
//        delegate?.scheduleNotification(at: selectedDate)
        delegate?.triggerNotification(at: selectedDate)
    }
}

Now I don't get to set new notification when tap on wait button. where do I have to set let NewDate = Date(timeInterval: 20, since: Date()) triggerNotification(at: NewDate)? I thought it went in case waitActionIdentifier but I don't even get the print to console.


Solution

  • The declaration of the category identifier was declared as private. Now the Notification actions work as expected. Thanks to VIP-DEV's answer I could find how to correct my code.