你能让应用程序在打开时显示本地通知吗?

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

我已经使用 UNUserNotificationCenter 设置了通知,但它们仅在应用未运行时显示 运行。有一些较旧的线程问同样的问题,但这些问题的答案对我不起作用,所以我想知道是否有更新的方法来做到这一点。

当应用程序处于前台和后台时,以下代码会触发 local notification

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])
    }
}