SwiftUI: how to send local notifications

tzJacky
3 min readApr 18, 2021
Photo by Angelo Burgener on Unsplash

This post shows you how to send local notifications.

What’s in a local notification?

The local notification includes two main parts:

  • Content: the content of a notification. It includes title, body, user info, etc.
  • Trigger: when to send a notification. It can be time, calendar, and location triggers.

After that, you wrap these two parts into a request and add this request to the user notification center.

How to send a local notification?

It has three steps:

  • Get the user notification center.
  • Request notification authorization.
  • Schedule a local notification.

Step 1: get the user notification center

import UserNotificationslet center = UNUserNotificationCenter.current()

Step 2: request notification authorization

center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in  if let error = error {  // Handle the error here.}}

Note that you don’t need to request the authorization every time, but you need to check the permission before you send a notification. You can achieve this by checking the notification setting.

center.getNotificationSettings { settings in  guard (settings.authorizationStatus == .authorized) ||    (settings.authorizationStatus == .provisional) else { return }  if settings.alertSetting == .enabled {    // Schedule an alert-only notification.  } else {    // Schedule a notification with a badge and sound.  }}

Step 3: deliver a local…

--

--