Local Notifications in iOS Apps

Jigyasaa Alemu Sood
The SDCoders
Published in
2 min readMay 13, 2021
Photo by Jamie Street on Unsplash

Often we want to send notifications to our users, outside of our application.

Notifications can be used to present alerts, play sounds or update our badge icon. We can use notifications to present important updates and grab our user’s attention.

There are two approaches to doing this:

  • Local notifications — scheduled and sent by the application itself
  • Push notifications — scheduled and sent by a cloud database / server connected to the application

In order to use push notifications, an Apple Developer Account is required. This is also very implementation-specific, since it is triggered from the cloud database or server end. For this reason, we cover local notifications here.

To send a local notification we need to create a UNMutableNotificationContent() which will store the details of our notification — such as the title, body and sound. We also establish a trigger to define when the notification will be sent

There are various triggers:

  • Time elapsed
  • Calendar dates / times
  • Locations

Each of these has a certain data type such as UNTimeIntervalNotificationTrigger, UNCalendarNotificationTrigger and UNLocationNotificationTrigger respectively.

We create a push notification by creating a UNNotificationRequest by providing an identifier, notification content and a trigger.

For our example we will demonstrate how to setup a time interval:

func displayNotifications(timing: Double) {

//local notifications need 3 objects: content, trigger and request
let content = UNMutableNotificationContent()
content.title = “Title!”
content.body = “This is a notification body, check it!”
content.sound = UNNotificationSound.default

//trigger defines when the notification will be sent
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: initialTiming, repeats: false) //time in seconds, if should be fired repeatedly

let request = UNNotificationRequest(identifier: “testIdentifier”, content: content, trigger: trigger)

//send the notification
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

--

--

Jigyasaa Alemu Sood
The SDCoders

Software Engineer | App Developer | Entrepreneur | TA @ CodePath