Create Local Notification

Notifications are inseparable parts of each iOS application. They are helpful to remind users about our app but at the same time, they can be the most annoying thing because who likes unlock iPhone and see dozens of notifications?

To show any kind of notification you need to ask the user for permission for that. Your app needs to handle both actions because you won’t be able to do it again, the user needs to grant permission in settings.

Firstly, you need to import UserNotifications.

import UserNotifications

Then you can ask for permission.

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
// Handle both cases when didAllow is true and false
}

You can use this method many times but only the first time the user will be asked. Later you get if permission is granted or not.

To create basic notification you can set the only title.

let content = UNMutableNotificationContent()
content.
title = “Greetings from SmashSwift”

Then create a request and add to the notification center.

let request = UNNotificationRequest(identifier: “identifier”, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

identifier is used to distinguish when the notification is clicked.
content is what will be displayed.
trigger is used to decide when to show notification, more about it in the next post. When it’s nil a notification is displayed immediately.

withCompletionHandler returns optional Error when adding request.

And it’s enough to show a notification.

However, you might encounter that nothing will be displayed. Why? Because your app is open. The default behavior is to not show anything. You can change it.

1. Open AppDelegate.swift.

2. Add:

import UserNotifications

3. Add UNUserNotificationCenterDelegate to AppDelegate. It should look like:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// content of App Delegate

4. Add:

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

With these 4 steps, you should see notification even when the app is open.

To UNMutableNotificationContent we sent the only title, but there are more options. To show text you can use, .title, .subtitle or .text. If you don’t set any of them then there won’t be any alert.

To show badge number to 1 set

content.badge = 1

The default value is 0 and it won’t be displayed.

To play some sound you need to set

content.sound = .default

Then the default sound will be used. You can create your own custom with UNNotificationSound.

By default, no sound is set.

Add Buttons To Notification

Some people always click on the notification and open app, some use buttons, but it’s worth to know how to add them.

Firstly, you need to create an array of UNNotificationAction.

var actions: [UNNotificationAction] = []

Then, create action:

let action = UNNotificationAction(identifier: “ButtonId”, title: “Click Me!”, options: .foreground)
actions.
append(action)

identifier is used to distinguish which button is clicked.
title is the text of a button.
options decide what type of button. The options are .foreground, .destructive or .authenticationRequired.

Next, create category and add it to notification center. You don’t need to create it every time you create a notification. Categories are reusable and can be bind to many notifications.

let category = UNNotificationCategory(identifier: “identifier”, actions: actions, intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])

The last thing is to edit notification content to bind with the notification category.

content.categoryIdentifier = “identifier”

categoryIdentifier need be the same as identifier in UNNotificationCategory.

How to recognize what was clicked?

Go back to AppDelegate.swift and add:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print(“Action id: \(response.actionIdentifier))
    completionHandler()
}

response.actionIdentifier is an identifier of a clicked button or if user clicks the notification. Here you can handle it.

When you click on “Click Me!” then you should see in the console.

Action id: ButtonId