Local notifications

UNUserNotificationCenter represents the central object for managing notification-related activities for your app or app extension. Typically the shared instance is used.

UNNotificationRequest represents a request to schedule a local notification, which includes the content of the notification and the trigger conditions for delivery.

UNMutableNotificationContent mutable content of a notification.

UNCalendarNotificationTrigger, UNTimeIntervalNotificationTrigger, or UNLocationNotificationTrigger classes represent conditions for delivering your notification.

UNUserNotificationCenterDelegate is the interface for handling incoming notifications and notification-related actions. You can implement this in AppDelegate object or UIViewController object.

1. Ask permission to use notifications. You can use provisional authorization to send notifications on a trial basis. Users can then evaluate the notifications and decide whether to authorize them.

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {


    func application(_ application: UIApplication, 
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) 
                     -> Bool {

    // ask permission
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound, .badge, .provisional]) { granted, error in
    
        if let error = error {
            // Handle the error here.
        }
    
        // authorization granted, so set
        // self as delegate for handling incoming notifications
        UNUserNotificationCenter.current().delegate = self
    }
}    

2. Prepare content and conditions of notification.

// prepare notification content
let content = UNMutableNotificationContent()
content.title = "Weekly Staff Meeting"
content.body = "Every Tuesday at 2pm"
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
content.sound = UNNotificationSound.default
content.launchImageName = "myimage"

// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3  // Tuesday
dateComponents.hour = 14    // 14:00 hours
   
// Create the trigger as a repeating event.    
let trigger = UNCalendarNotificationTrigger(
         dateMatching: dateComponents, repeats: true)

3. Shedule notification.

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


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

// cancel if necessary
notificationCenter.removePendingNotificationRequests(uuidString)

4. Handle notifications.

import UserNotifications

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(
      _ center: UNUserNotificationCenter, 
      didReceive response: UNNotificationResponse, 
      withCompletionHandler completionHandler: @escaping () -> Void) {
    
        switch response.actionIdentifier {
            case UNNotificationDefaultActionIdentifier:
                print("User opened notification.")
            case UNNotificationDismissActionIdentifier:      
                print("User dismissed notification.")

            default:
                print("Unknown identifier")
        }
    
       completionHandler()
    }
}    

extra actions

Notifications may have extra actions.

UNNotificationCategory defines the type of notifications that your app supports.

UNNotificationAction defines the button to display for each notification type.

1. Register extra actions.

// call when app did finish launching  
  func setupUNNotificationCategory() {
    // simple button
    let action1 = UNNotificationAction(identifier: "action1", 
                                       title: "action 1", 
                                       options: [.destructive])
    
    let action2 = UNNotificationAction(identifier: "action2", 
                                       title: "action 2", 
                                       options: [.authenticationRequired])
                                       
    let action3 = UNNotificationAction(identifier: "action3", 
                                       title: "action3", 
                                       options: [.foreground])

   
    // Add actions to a category
    let actions = [action1, action2, action3]
    let category = UNNotificationCategory(
                            identifier: "appCategoryId", 
                            actions: actions, 
                            intentIdentifiers: ["appIntentIdentifiers"], 
                            options: [.customDismissAction])

    // Set category to NotificationCenter
    UNUserNotificationCenter.current().setNotificationCategories([category])
  }
}

There are 3 types of actions:

  • destructive - action performs a destructive task
  • authenticationRequired - action can be performed only on an unlocked device
  • foreground - action causes the app to launch in the foreground

2. Add action handling to the notify handling.

import UserNotifications

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(
      _ center: UNUserNotificationCenter, 
      didReceive response: UNNotificationResponse, 
      withCompletionHandler completionHandler: @escaping () -> Void) {
    
        switch response.actionIdentifier {
            case UNNotificationDefaultActionIdentifier:
                print("User opened notification.")
            case UNNotificationDismissActionIdentifier:      
                print("User dismissed notification.")

            case "action1", "action2", "action3":
                print("Extra action is triggered.")

            default:
                print("Unknown identifier")
        }
    
       completionHandler()
    }
}