In this short Swift code example, you will learn how to 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. The application will be able to receive a message, play a sound when a local notification message arrives and display a notification badge in the upper corner of the application icon,
- Check if the 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 the message is received,
- Assign default sound UILocalNotificationDefaultSoundName to local notification message,
- Implement code to receive the local notification message and display message content as an Alert dialog window to the 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: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (granted, error) in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } else{ print(error?.localizedDescription ?? "Something went wrong") } } return true }
Receive Local Notification Message(UILocalNotification)
Add the below code to your AppDelegate.swift file to enable your app to listen for local notification messages and display an alert dialog window with the message content when the message arrives.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo print(userInfo) if let aps = userInfo["aps"] as? [ String : Any ] { print(aps) } completionHandler([.alert, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Get the meeting ID from the original notification. let userInfo = response.notification.request.content.userInfo print(userInfo) if let aps = userInfo["aps"] as? [ String : Any ] { print(aps) } // Always call the completion handler when done. completionHandler() }
Create and Schedule UILocalNotification
let identifier = "learn-swift" let notificationContent = UNMutableNotificationContent() notificationContent.body = "You have a new message. Tap here to read it." notificationContent.sound = UNNotificationSound.default notificationContent.badge = 1 notificationContent.userInfo = ["customParameterKey_from": "Sergey"] // Array of custom let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false) let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { print("Error: \(error)") return } }
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: .system) as UIButton let xPostion:CGFloat = 50 let yPostion:CGFloat = 100 let buttonWidth:CGFloat = 250 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: .normal) button.tintColor = UIColor.black button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside) self.view.addSubview(button) } @objc func buttonAction(_ sender: UIButton) { let current = UNUserNotificationCenter.current() current.getNotificationSettings(completionHandler: { (settings) in if settings.authorizationStatus == .authorized { DispatchQueue.main.async { if settings.alertSetting.rawValue == 2 { print("Alert is allowed") self.scheduleLocalNotification() } if settings.badgeSetting.rawValue == 2 { //Have badge permission print("Badge is allowed") } if settings.soundSetting.rawValue == 2 { //Have badge permission print("Sound is allowed") } } }else { print("Notification is not allowed") } }) } func scheduleLocalNotification() { let identifier = "learn-swift" let notificationContent = UNMutableNotificationContent() notificationContent.body = "You have a new message. Tap here to read it." notificationContent.sound = UNNotificationSound.default notificationContent.badge = 1 notificationContent.userInfo = ["customParameterKey_from": "Sergey"] // Array of custom let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false) let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { print("Error: \(error)") return } } } }
Complete Example of AppDelegate.swift file
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (granted, error) in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } else{ print(error?.localizedDescription ?? "Something went wrong") } } return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo print(userInfo) completionHandler([.alert, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Get the meeting ID from the original notification. let userInfo = response.notification.request.content.userInfo print(userInfo) // Extract custom parameter value from notification message let customParameterValue = userInfo["customParameterKey_from"]! as! String print("Message from sent by \(customParameterValue)") // Extract message alertBody let messageToDisplay = response.notification.request.content.body // 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) // Always call the completion handler when done. completionHandler() } }
For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.