Local Notifications on iOS

Local Notifications on iOS

Notifications are important when buiding an iOS app. For the application I am currently working on, a day planner app, I needed to trigger local notifications. Here this code I used to schedule a notification:

// create a new notification content
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "This is the title of the notification"
notificationContent.subtitle = "This is the subtitle"
notificationContent.sound = UNNotificationSound.default

// create the date 
let date = Calendar.current.date(byAdding: .hour, value: 1, to: Date.now)! // ugly force unwrap, but this is an example

// create the date components for the trigger
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)

// Create the trigger 
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

// Create the notification request
let request = UNNotificationRequest(identifier: task.id.uuidString, content: notificationContent, trigger: trigger)

// Add the request to 
UNUserNotificationCenter.current().add(request) { error in
    if let error {
        print(error.localizedDescription)
        // here you can handle the error
    }
}

But before trying to run this code, you will need to ask the user for the notification permission. Modify the info.plist file to indicate why you need the notification permission. The item you’re looking for is: Privacy - User Notifications Usage Description. If you prefer editing the info.plist as code, you can right click on the info.plist, then click on Open As and select Source Code. Here is the key and the value you need to add or modify:

<key>NSUserNotificationsUsageDescription</key>
<string>We need the notification permission to send you notifications.</string>

Finally, here is the snippet to ask the notification permission to the user:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { success, error in
    if error == nil && success {
        // handle the success case 
    } else {
        // handle failure 
    }
} 

And that’s it. The user is now able to receive local notifications from your app if he accepts the notifications permission request.






Register to the newsletter