Search code examples
iosswiftuilocalnotification

Can you make an app display a local notification while it's open?


I've set up notifications with UNUserNotificationCenter but they're only displayed when the app isn't running. There's some older threads asking the same question but the answers to those aren't working for me so I'm wondering if there's an updated way to do it.


Solution

  • The below code triggers local notification when app is in foreground and background.

    import UIKit
    import UserNotifications
    
    class ViewController: UIViewController, UNUserNotificationCenterDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //requesting for authorization
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
                    if error == nil {
                        self.triggerLocalNotification()
                }
            })
        }
    
        func triggerLocalNotification(){
    
            //creating the notification content
            let content = UNMutableNotificationContent()
    
            //adding title, subtitle, body and badge
            content.title = "Notification title "
            content.subtitle = "Notification sub-title "
            content.body = "We are learning about iOS Local Notification"
            content.badge = 1
    
            //it will be called after 5 seconds
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
            //getting the notification request
            let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
    
            UNUserNotificationCenter.current().delegate = self
    
            //adding the notification to notification center
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
            //displaying the ios local notification when app is in foreground
            completionHandler([.alert, .badge, .sound])
        }
    }