Create local notification in swift for iOS app

Create local notification in iOS using swift 5

In this post, we are going to learn how to create local notifications in swift for iOS app using USerNotifications framework. Local notifications are most commonly used in iOS apps like alarm app,  ToDO reminder etc. So let us start and learn how we can integrate local notification using swift language for iOS app. Follow the given below steps, to integrate or add local notifications in swift to your app.

Step 1:  Create a single view application project.

Step 2: Open “AppDelegate.swift” file, import “UserNotifications” framework. First we need to ask user to give our app permissions to send him notifications. Add below code, to did Finish Launching With Options method of UIApplicationDelegate.

UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("User gave permissions for local notifications")
            }
        }

Step 3: Make AppDelegate class to conform to UNUserNotificationCenterDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {  

Designing user interface

Step 4: Open main.storyboard file and in view-controller, drag a UIButton on to view. Set title for UIButton as “Set Reminder”. Apply constraint as shown in image

Creating user interface for out tutorial create a local notification in ios using swift 5
User interface for the app
Setting constrain to our UIButton - Create local notification in iOS using swift 5
Constraints set for UIButton

Step 5: Open “Viewcontroller.swift” file. Create an IBAction for the UIButton.

    @IBAction func setReminder(_ sender: Any){
	}

Step 6: Open Main.storyboard file. Connect, recently created IBAction to touchupinside event of UIButton.

Registering local notification to iOS

It’s time to write code to, create a local notification for our app for a certain date.

    @IBAction func setReminder(_ sender: Any){
        let center = UNUserNotificationCenter.current()
        let content = UNMutableNotificationContent()
        content.title = "Notifiaction on a certail date"
        content.body = "This is a local notification on certain date"
        content.sound = .default
        content.userInfo = ["value": "Data with local notification"]
        let fireDate = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: Date().addingTimeInterval(20))
        let trigger = UNCalendarNotificationTrigger(dateMatching: fireDate, repeats: false)        
        let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
        center.add(request) { (error) in
            if error != nil {
                print("Error = \(error?.localizedDescription ?? "error local notification")")
            }
        }
        
    }

In above code, first we get instance of current notification center. Next we are creating content for our notification. Content object will have, the info you want to show on your notification to the user. It includes

  • title: Title for the notification
  • body: message associated with the notification.
  • sound: you can give sound to your notification (in our case its default)
  • userInfo: the information you want to associate with local notification. This is useful in cases, where we want to check the data associated with notification.

After setting information to our local notification. Its time to set date for our notification to be shown on user phone. Next, we will create a trigger object that full fill the condition for notification. If you, want to repeat notification then set repeats parameter to true. Finally we will create a request for our notification, and add it to current notification center.

Testing for local notification

If you run your app and tap on tap on button to set reminder. After 20 second, you will see notification on iPhone lock screen.

Local notification displayed on iPhone  - Create local notification in iOS using swift 5
Local notification displayed on iPhone

If you did not get notification, then try to follow all steps carefully.

Handling UNUserNotificationCenter delegate

In case of local notification, we have to implement two delegate methods

  • will present notification
  • did receive response

The first delegate method, will allow us to show notification to user when app is running in foreground. Second one will gets called when user tap on notification.

Implementing notification center delegates

    //MARK:- UNUSerNotificationDelegates
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        completionHandler([.alert, .badge, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Usrinfo associated with notification == \(response.notification.request.content.userInfo)")

        completionHandler()
    }

In above code, will present delegate is only calling completion handler. Thus displaying notification when app is running in foreground. The did receive response delegate will print the user-info associated with the local notification, as soon as user tap on the notification.

Source code for local notification in ios

Download the source code from https://github.com/leoiphonedev/LocalNotificationSwift5-Tutorial

Where to go from here

In this tutorial, we learned about how to add local notification in swift. If you have any issues, the please try to re-follow the steps. If you still have any issues, then feel free to drop us comments or contact us.