others-how to show notification even if the app is in forground in iOS app

Problem

When we develop iOS app to show local notification programmatically, we found that when the app is in foreground, the notification can not be shown. What should we do if we want to show notification in iOS app even if the app is in foreground?

Environment

  • iOS programming
  • XCode 11.3
  • Swift 5

Code

Step #1: Add protocol to your AppDelegate

Change your AppDelegate to add a UNUserNotificationCenterDelegate like this, and then implement the function: userNotificationCenter :

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    ....
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler(.alert)
    }

}

Step #2: Show notification

Let’s create a button, and when user click the button, let’s show the notification.

@IBAction func onNotifTestClicked(_ sender: Any) {
    let current = UNUserNotificationCenter.current()

    // Defines what kinds of notifications we send --
    // in our case, a simple alert
    let notificationOptions : UNAuthorizationOptions = [.alert]
    // The switch was turned on.
    // Ask permission to send notifications.
    current.requestAuthorization(options: notificationOptions,completionHandler: { (granted, error) in
        if granted {
                   // We've been granted permission. Queue the notification.
            self.addNotificationRequest()
            
        }else if let error = error {
            print(error.localizedDescription)
        }
    })
}

func addNotificationRequest() {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    let content = UNMutableNotificationContent()
    content.title = "New notification"
    content.subtitle = "Notification content example."
    content.sound = UNNotificationSound.default

    // show this notification five seconds from now
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    // choose a random identifier
    let request = UNNotificationRequest(identifier: self.notificationId,
                                        content: content, trigger: trigger)

    // add our notification request
    UNUserNotificationCenter.current().add(request)
}