Local Notifications: Getting Started

Learn how to create notifications by time intervals, time of day and location, as well as how to support category grouping and prompting for action. By Vidhur Voora.

5 (9) · 1 Review

Download materials
Save for later
Share

Notifications are an integral way of conveying information to the user outside of an app. They help draw users’ attention and drive their engagement with the app. But a burst of notifications can annoy users, causing them to turn them off or even delete the app. So you must use notifications wisely.

There are two types of notifications: local and remote. This tutorial is all about local notifications. In this tutorial, you’ll learn how to:

  • Request permission for notifications.
  • Create, schedule and manage different types of local notifications.
  • Handle notification actions.

Often, users forget about tasks and need a reminder. You’ll make it easy to remind them using the power of local notifications.

Getting Started

Download the project by clicking the Download Materials button at the top or bottom of this page. Open the OrganizerPlus project. Build and run.

OrganizerPlus Overview

OrganizerPlus helps keep track of your tasks. Tap the + button to start creating a task. Next, add a name for the task and tap Save. You can mark the task as completed by tapping the circle next to the task.

Introducing Notifications

Notifications can be either local or remote. The app on the device schedules and configures local notifications. In contrast, a server sends remote notifications using Apple Push Notification Service (APNS). A news alert is an example of a remote notification where the server sends the latest breaking news to the device as a notification.

Remote notifications can be both visible and silent. Silent notifications launch the app in the background to perform an action, such as refreshing the app. You can configure both local and remote notifications using the UserNotifications framework. To learn more about remote notifications, check out Push Notifications Tutorial: Getting Started.

Contrasting Local and Push Notification Processes

To create and manage notifications, you need the following steps:

  • Authorization
  • Content creation
  • Scheduling the notifications
  • Managing the notifications
  • Handling actions

You’ll learn how to do each of these steps in this tutorial.

Requesting Notification Permission

Notifications interrupt the user, so an app needs the user to allow them. In OrganizerPlus, you’ll request notification permission when the user taps the bell button at the top right.

First, open NotificationManager.swift. Then, add the following to NotificationManager:

func requestAuthorization(completion: @escaping  (Bool) -> Void) {
  UNUserNotificationCenter.current()
    .requestAuthorization(options: [.alert, .sound, .badge]) { granted, _  in
      // TODO: Fetch notification settings
      completion(granted)
    }
}

Here’s what the code does:

  • UNUserNotificationCenter handles all notification-related behavior in the app. This includes requesting authorization, scheduling delivery and handling actions. You can access the shared instance of UNUserNotificationCenter by calling current().
  • You invoke requestAuthorization(options:completionHandler:) to request authorization to show notifications. options denotes the notification’s behavior, such as displaying an alert, playing a sound or updating the app’s badge. You can learn more about the various UNAuthorizationOptions in the developer documentation.
  • The completion handler receives a Boolean that indicates whether the user granted the authorization. Here, you call the completion handler with the Boolean value. The TODO comment is a placeholder to fetch notification settings. You’ll implement this next.

Now, add the following in NotificationManager:

func fetchNotificationSettings() {
  // 1
  UNUserNotificationCenter.current().getNotificationSettings { settings in
    // 2
    DispatchQueue.main.async {
      self.settings = settings
    }
  }
}

Here’s what you added:

  • UNUserNotificationCenter‘s getNotificationSettings(completionHandler:) requests the notification settings authorized by the app. The settings return asynchronously. UNNotificationSettings manages all the notification-related settings and the authorization status of the app. settings is an instance of it.
  • The completion block may be called on a background thread. Here, you update the settings property on the main thread as changing its value updates the UI.

Now, replace // TODO: Fetch notification settings in requestAuthorization(completion:) with the following:

self.fetchNotificationSettings()

Here, you fetch the notification settings after the user has granted the authorization.

Prompting Notification Authorization

Open TaskListView.swift. Then, find // TODO: Add Notification authorization in the action closure of the button and replace it with the following:

// 1
NotificationManager.shared.requestAuthorization { granted in
  // 2
  if granted {
    showNotificationSettingsUI = true
  }
}

Here’s a breakdown:

  1. You request the notification authorization by calling requestAuthorization(completion:), which you defined in NotificationManager.
  2. If the user granted permission, you set showNotificationSettingsUI to true. This presents NotificationSettingsView as a sheet.

Build and run.

Notification Permissions Prompt

Tap the bell icon at the top right. This prompts the notification authorization. Next, select Allow. You’ll see the list of notification settings granted by the app.

Nice job getting through the first step of notification management!

Understanding Critical Notifications

In the notification settings, notice that the app doesn’t have authorization for critical alerts. But what are critical alerts?

Critical alerts are health, medical, security or public safety notifications. They bypass the do-not-disturb and ringer switch and play a sound. These are quite disruptive, so not all apps can send critical alerts.

If your app needs to send them, you can apply for entitlement on the Apple developer portal.

Reminders from OrganizerPlus are important but not critical, so you don’t need to enable critical alerts for this tutorial. :]

Now, it’s time to create and schedule notifications.

Creating Notifications

You can create and schedule local notifications using any of the following triggers:

  • Time interval
  • Calendar
  • Location

These options determine when your app delivers the notification. For your next step, you’ll learn to create notifications using each of these triggers.

Triggering TimeInterval Notifications

Open NotificationManager.swift and add the following to NotificationManager:

// 1
func scheduleNotification(task: Task) {
  // 2
  let content = UNMutableNotificationContent()
  content.title = task.name
  content.body = "Gentle reminder for your task!"

  // 3
  var trigger: UNNotificationTrigger?
  switch task.reminder.reminderType {
  case .time:
    if let timeInterval = task.reminder.timeInterval {
      trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: timeInterval,
        repeats: task.reminder.repeats)
    }
  default:
    return
  }

  // 4
  if let trigger = trigger {
    let request = UNNotificationRequest(
      identifier: task.id,
      content: content,
      trigger: trigger)
    // 5
    UNUserNotificationCenter.current().add(request) { error in
      if let error = error {
        print(error)
      }
    }
  }
}

Here’s what you added:

  1. scheduleNotification(task:) takes in a parameter of type Task. That’s your model, which holds all the data related to any task. It’s defined in Task.swift.
  2. You start creating a notification by populating the notification content. UNMutableNotificationContent holds the payload for a local notification. Here, you populate the title and body of the notification. UNMutableNotificationContent has other properties, such as:
    • subtitle: A secondary description for the notification.
    • badge: The number to display for the app’s icon badge.
    • sound: The sound to play during notification delivery.
    • attachments: An array of attachments to display in the notification. These could be images, video or audio files.
  3. UNNotificationTrigger is an abstract class that triggers the delivery of a notification. Here, you check if the reminderType of the task is time-based with a valid time interval. Then, you create a time interval-based notification trigger using UNTimeIntervalNotificationTrigger. You use this type of trigger to schedule timers. In addition to taking a timeInterval, the constructor takes in a Boolean parameter, repeats. This determines whether the notification needs to reschedule after being delivered. You’ll handle the other cases of the switch later in this tutorial.
  4. After trigger definition, the next step is to create a notification request. You create a new request using UNNotificationRequest and specifying an identifier, content and a trigger. Each task you create already has a unique identifier. You’ll pass that as the notification identifier.
  5. Then, you schedule the notification by adding the request to UNUserNotificationCenter. The completion handler has an error object that indicates if a problem occurred when scheduling a notification.