NS

Schedule Notifications and Add Badges to your iOS apps in SwiftUI

After reading this article, you should be able to quickly add local notifications to your app. Let us learn a little more about each of the terms in the title.

SwiftUI

“SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs.” — Apple’s official documentation

The best part is you can integrate your views with components from the UIKit, AppKit, and WatchKit frameworks. In short, SwiftUI has made building user interfaces straightforward.

Local Notifications

“Use local notifications to get the user’s attention. You can display an alert, play a sound, or badge your app’s icon. For example, a background app could ask the system to display an alert when a particular task is finished. Always use local notifications to convey important information that the user wants.

The delivery of notifications is handled by the system, based on a time or location that you specify. If the delivery of the notification occurs when your app is not running or in the background, the system interacts with the user for you. If your app is in the foreground, the system delivers the notification to your app for handling.” — Apple’s official documentation

Badges

Every iOS app has one instance of UIApplication, which provides control to manage your app’s icon. You can add a number on the top right of your app’s icon, set an alternate icon (change app’s icon), etc.

This is pretty much all we need to know to get started. Let’s dive into notifications.

Notifications

To push notifications to the lock screen, we need to do two things:

  1. Ask for user permission to send notifications.
  2. Trigger notifications.

We will start with using the UserNotifications framework. To ask for user permissions in order to push notifications to the lock screen, you could simply write:

   if success {
       print("User Accepted")
   } else if let error = error {
       print(error.localizedDescription)
  }
}

Now that we are authorized to send notifications, let us start working on the trigger mechanism.

Firstly, we will create content:

let content = UNMutableNotificationContent()  
content.title = "Daily Notification"  
content.body = "Daily Notification is Ready"  
content.sound = UNNotificationSound.default //you can play with it

The next step is to create a schedule. Now you could either schedule it daily, weekly, monthly, or every five minutes. All these parameters can easily be manipulated. For example:

Push a notification every day at 2 p.m. local time

var dateComponents = DateComponents()  
dateComponents.hour = 11  
dateComponents.minute = 59  
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

Push a notification every 10 seconds

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

Note: You cannot set the repeats to _true_ until your _timeInterval_ is set to at least 60.

Now that we have a schedule set up, we need to set up a request to trigger notifications:

let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

Finally, add the request:

UNUserNotificationCenter.current().add(request)

One really important thing to note is if you are testing or executing this piece of code every time your app loads, you will have multiple requests added to UNUserNotificationCenter. As a result, you will be getting multiple notifications over and over again. To avoid that, it is important that you remove all pending notification requests that are already scheduled before adding the request. To do that:

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

That’s it! You have notifications working for your app. You will be notified even if you close the app, lock your phone, or simply move your app to the background.

Badge Number

Once you have notifications working, showing a badge number is a cakewalk. I will assume that your app user has already authorized you to send notifications. With that, you can just add the following line anywhere in your app:

UIApplication.shared.applicationIconBadgeNumber = badgeNumber //Integer

Here is the full code for the go-getters:

  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("Success")
              //To add badgeNumber
              //UIApplication.shared.applicationIconBadgeNumber = badgeNumber (Integer Value)
              
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
        
        
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        let content = UNMutableNotificationContent()
        content.title = "Daily Notification"
        content.body = "Daily Notification is Ready"
        content.sound = UNNotificationSound.default

        var dateComponents = DateComponents()
        dateComponents.hour = 11
        dateComponents.minute = 59
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
//        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request)
}

There you go! Now you have scheduled notifications and added a badge number to your app icon.

Thanks for reading!