UILocalNotification. Create, Schedule and Receive Local Notifications in Swift

In this short Swift code example we will learn how make our mobile app register for local notifications and how to create, schedule and display Local Notifications(UILocalNotification) in Swift. The code below will cover:

  • Register for Local Notifications. Application will be able to receive message, play sound when local notification message arrives and display notification badge in the upper corner of application icon,
  • Check if application has been successfully registered for local notifications and which notification types are supported. In the example below we will support Alert, Sound and Badge.
  • Create UILocalNotification and schedule it to display in 5 seconds,
  • Additionally to notification alert message, include custom parameters which we can then extract when message is received,
  • Assign default sound UILocalNotificationDefaultSoundName to local notification message,
  • Implement code to receive local notification message and display message content as an Alert dialog window to user,
  • Extract UILocalNotification custom parameters sent with the UILocalNotification message object.

Register for Local Notifications(UILocalNotification)

To make your application registered for local notification messages update your AppDelegate.swift file with the below code. The didFinishLaunchingWithOptions function should already exist in your AppDelegate.swift file, so you will most probably only need to update its content.

  
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(notificationSettings)
    
        return true
    }

Receive Local Notification Message(UILocalNotification)

Add the below code to your AppDelegate.swift file to enable your app listen for local notification messages and display alert dialog window with the message content when the message arrives.

 
    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
        
         print("Print entire notification message for preview:  \(notification)")
        
         let userInfoObject = notification.userInfo! as! [String : String]
        
         // Extract custom parameter value from notification message
         let customParameterValue = userInfoObject["customParameterKey_from"]! as String
         print("Message from sent by \(customParameterValue)")
        
        // Extract message alertBody
        let messageToDisplay = notification.alertBody
        
        // Display message alert body in a alert dialog window
        let alertController = UIAlertController(title: "Notification", message: messageToDisplay, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "Ok", style: .default) { (action:UIAlertAction!) in
  
            print("Ok button tapped");
            
        }
        alertController.addAction(OKAction)
        
        // Present dialog window to user
        window?.rootViewController?.present(alertController, animated: true, completion:nil)
    } 

Create and Schedule UILocalNotification

 
        let notification = UILocalNotification()
        notification.fireDate = NSDate(timeIntervalSinceNow: 5) as Date
        notification.alertBody = "You have a new message. Tap here to read it."
        notification.alertAction = "Ok" //  used in UIAlert button or 'slide to unlock...' slider in place of unlock
        notification.soundName = UILocalNotificationDefaultSoundName
        notification.userInfo = ["customParameterKey_from": "Sergey"] // Array of custom parameters
        notification.applicationIconBadgeNumber = 1
        UIApplication.shared.scheduleLocalNotification(notification)

Create and Schedule UILocalNotification Complete Example in Swift

 
import UIKit

class ViewController: UIViewController  {
   
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // Create a button which when tapped will register local notification message
        let button = UIButton(type: UIButtonType.system) as UIButton
        
        let xPostion:CGFloat = 50
        let yPostion:CGFloat = 100
        let buttonWidth:CGFloat = 150
        let buttonHeight:CGFloat = 45
        
        button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)
        
        button.backgroundColor = UIColor.lightGray
        button.setTitle("Tap to register local notification", for: UIControlState.normal)
        button.tintColor = UIColor.black
        button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside)
        
        self.view.addSubview(button)

    }
    
    func buttonAction(_ sender:UIButton!)
    {
        var notificationsAllowed = false;
        
        if let settings = UIApplication.shared.currentUserNotificationSettings
        {
            if settings.types.contains([.alert])
            {
                //Have alert and sound permissions
                notificationsAllowed = true;
            }
            
            if settings.types.contains([.badge])
            {
                //Have badge permission
                print("Badge is allowed")
            }
            
            if settings.types.contains(.sound)
            {
                //Have alert permission
                print("Sound is allowed")
            }
        }
        
        if notificationsAllowed
        {
            scheduleLocalNotification()
        }

    }
    
    func scheduleLocalNotification()
    {
        let notification = UILocalNotification()
        notification.fireDate = NSDate(timeIntervalSinceNow: 5) as Date
        notification.alertBody = "You have a new message. Tap here to read it."
        notification.alertAction = "Ok" //  used in UIAlert button or 'slide to unlock...' slider in place of unlock
        notification.soundName = UILocalNotificationDefaultSoundName
        notification.userInfo = ["customParameterKey_from": "Sergey"] // Array of custom parameters
        notification.applicationIconBadgeNumber = 1
        UIApplication.shared.scheduleLocalNotification(notification)
    }
 
    
}

Complete Example of AppDelegate.swift File

 
import UIKit


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(notificationSettings)
    
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
        
         print("Print entire notification message for preview:  \(notification)")
        
         let userInfoObject = notification.userInfo! as! [String : String]
        
         // Extract custom parameter value from notification message
         let customParameterValue = userInfoObject["customParameterKey_from"]! as String
         print("Message from sent by \(customParameterValue)")
        
        // Extract message alertBody
        let messageToDisplay = notification.alertBody
        
        // Display message alert body in a alert dialog window
        let alertController = UIAlertController(title: "Notification", message: messageToDisplay, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "Ok", style: .default) { (action:UIAlertAction!) in
  
            print("Ok button tapped");
            
        }
        alertController.addAction(OKAction)
        
        // Present dialog window to user
        window?.rootViewController?.present(alertController, animated: true, completion:nil)
    }

}

Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon