在前台显示应用程序的通知

Display notification with the app in the foreground

我有一个 iOS flutter 应用程序,我想在该应用程序位于前台时显示本地通知。

我要粘贴的代码在应用程序处于后台时有效,但在打开时无效。

创建通知:

        // Create notification content
        let content = UNMutableNotificationContent()
        content.title = title
        content.sound = UNNotificationSound.default
        
        // Set trigger
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
        
        // Submit request
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        
        center.add(request) { (error : Error?) in
            if let theError = error {
                print(theError.localizedDescription)
            }
        }

方法中:

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
}

受其他对同一问题的回应的驱动,我添加了以下内容:

        if #available(iOS 10.0, *) {
          UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
        }

None 以上作品。如果应用程序在前台,则不会显示通知。

如何在前台显示本地通知?

使用flutter_local_notifications显示通知

在 iOS 上,系统不会自动显示当您的应用 运行 在前台时发送的通知。

来自the documentation

If your app is in the foreground, the system delivers the notification to your app for handling.

您需要实施 userNotificationCenter(_:willPresent:withCompletionHandler:) delegate function and call the provided completion handler with the desired presentation option, probably .banner

func userNotificationCenter(_ center: UNUserNotificationCenter, 
                         willPresent notification: UNNotification, 
               withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(.banner)
}

您需要在适当的地方建立您的通知中心委托,例如didFinishLaunching