Local Notifications using UserNotifications Class - Swift, iOS - Swift 4 Tutorials W3Schools


Post Top Ad

31 Aug 2017

Local Notifications using UserNotifications Class - Swift, iOS

Local Notifications are mainly used in iOS apps for notifying user when new data or information available for your app.This will notify, even if the app is background.

Earlier we were using UILocalNotification class for sending local notification, now UILocalNotification deprecated in iOS 10.

From iOS 10 apple introduced new class called UserNotifications for sending or receiving notification. We can use UserNotifications for both Local Notification & Remote Notifications.

This Article Covers All Related questions  :

How to schedule a local notification in iOS 10 Swift.
Introduction to User Notifications Framework in iOS 10.
How To Set Up iOS 10 Local Notifications.
How to Make Local Notifications in iOS 10.

Notification center with LOCAL NOTIFICATION

UserNotifications :

UserNotifications framework used for delivery and handling of Local Notification & Remote Notifications. We can use this UserNotifications class for schedule the delivery of local notification based on either time or location. Apps and extensions also use this framework to receive and potentially modify local and remote notifications when they are delivered to the user’s device.

Local Notification :

With this, our app configures the notification details locally and passes those details to the system, which then handles the delivery of the notification when your app is not in the foreground.

When to Use :

Local notification can be used based on app data and functionality. Mostly used because, always apps are not running in foreground so we can alert user when a new information is downloaded from server, or may be from local data.

Local notification and Remote notification both same in appearance, when presented on a given device.

For delivering notification we are having 3 options, we can choose one of the following :

1. An onscreen alert or banner
2. A badge on your app’s icon
3. A sound that accompanies an alert, banner, or badge

Example Project:

First create a new project  open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'LocalNotifications-swift' then tap next and select the folder to save project.

For sending notification we need some action to be done, for that we are adding button to view of ViewController.

Let’s get started by first declaring a property of type UIButton and give auto layouts, title as we requires. Add the following methods to ViewController.swift file:
func addingButton() {
    let sendButton = UIButton()
    sendButton.translatesAutoresizingMaskIntoConstraints = false
    sendButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    sendButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    sendButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
    sendButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
    sendButton.setTitle("Send Notification", for: .normal)
    sendButton.setTitleColor(UIColor.white, for: .normal)
    sendButton.backgroundColor = UIColor.blue
    sendButton.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)

@objc func buttonTapped(sender: UIButton) {


Call addingButton() inside viewDidLoad() method.

Now Run, we will see Button at center of View looks as :

Notifications Button

RequestAuthorization :

Now , let's dive into notification setup, delivery..

Firstly, we need to configure the app. That means we need to ask the user authentication whether device needs to get notification or not.

To request authorization, call the requestAuthorizationWithOptions:completionHandler: method of the shared UNUserNotificationCenter object.

Replace viewDidLoad() with following method :
override func viewDidLoad() {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        if (granted) {
        }else {
            print(error?.localizedDescription as Any)

Build and Run, we will see alert with notification request permissions. Tap 'Allow' for testing, if not then we don't receive any notification.

RequestAuthorization Notifications

Send Notification with Content :

Secondly, we need to send notification, so we are creating UNMutableNotificationContent object for setting up content. Add the following code inside buttonTapped() method :
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Good morning!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Wake up! It's morning time!",
                                                        arguments: nil)
content.sound = UNNotificationSound.default()

So we created UNMutableNotificationContent with title,body and sound. There are more but for us it will be enough.

Next step is trigger, when to trigger there are several trigger methods but we are using UNTimeIntervalNotificationTrigger. Add following line at the end of buttonTapped() method :
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:TimeInterval(10)  , repeats: false)

Here we are giving time interval as 10 sec, that means after tapping button then in next 10 seconds we will get notification.

Then we need request object. Add following line at the end of buttonTapped() method :
let request = UNNotificationRequest(identifier: "MorningAlarm", content: content, trigger: trigger)

Finally, we need to schedule the request using UNUserNotificationCenter object. Add following code at the end of buttonTapped() method :
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
    if let theError = error {

Build and run, Then tap on notification button and lock the device. After 10 sec we will get Local Notification.

Notification center with LOCAL NOTIFICATION

UNUserNotificationCenterDelegate :

Great we are getting notification, but how to handle after receiving. Good for that we have delegates in place.

so add the following line of code to the end of viewDidLoad() method :
center.delegate = self

There are two delegates methods for handling notifications.

Foreground :

First one userNotificationCenter:willPresentNotification:withCompletionHandler: is for handling when app is running in foreground.

Add the following delegate method :
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Play a sound.

The completionHandler receives input as UNNotificationPresentationOptions. we used sound option, so when received notification in foreground we get notified with sound.

Background :

Second one userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: is for handling when user taps on notification while app is running in background.

Add the following delegate method :
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {

This delegate method will call when user taps on notification.

Inside delegate methods we need to handle our data based on app functionality.

Build and Run the app, Then tap on button then check both cases in Background and Foreground. we will see logs in console.

In next article, we will go through Custom actions on Notifications.

Download sample project with examples :

No comments:

Post a Comment

Post Top Ad