在 iOS 10 中,当应用程序位于前台时,不会调用“willPresent notification”,并且不会显示本地通知

Mic*_*ons 5 ios uilocalnotification ios-simulator swift unusernotificationcenter

当我第一次运行我的应用程序时,模拟器能够在应用程序位于前台时显示通知。

当我重新启动应用程序didReceive notification:(即 iOS 9 中的通知方法)时,将调用willPresent notification(即 iOS 10 中的通知方法),并且当应用程序位于前台时不会显示任何通知。但是,如果应用程序在后台运行,则会显示通知。

这个问题或这个问题都没有提供这个问题的解决方案。

我使用以下代码获得通知授权:

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]? = [:]) -> Bool {
                if #available(iOS 10.0, *) {
                    let center = UNUserNotificationCenter.current() 
                    center.requestAuthorization(options: [.alert, .sound,  .sound]) { (granted, error) in              
                    UNUserNotificationCenter.current().delegate = self                   
                    }                      
                }
                return true
            }
Run Code Online (Sandbox Code Playgroud)

我已经实现了 willPresent 通知方法:

@available(iOS 10.0, *)
            func userNotificationCenter(_ center: UNUserNotificationCenter,
                                        willPresent notification: UNNotification,
                                        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)                     completionHandler(UNNotificationPresentationOptions.alert)
            }
Run Code Online (Sandbox Code Playgroud)

以下是我创建通知的方法:

let content = UNMutableNotificationContent()
        content.title = title
        content.subtitle = subtitle
        content.body = message
        content.categoryIdentifier = identifier                      

        let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: 10.0,
            repeats: false)

        let request = UNNotificationRequest(
            identifier: "identifier",
            content: content,
            trigger: trigger
        )

        UNUserNotificationCenter.current().add(
            request, withCompletionHandler: nil)
Run Code Online (Sandbox Code Playgroud)

简而言之,问题是:如何确保应用程序在第一次运行后位于前台时能够显示通知?

提前致谢。

Jer*_*rry 3

尝试在完成块之外设置委托requestAuthorization。它可能发生的时间比你想要的要晚。

我在这里添加了一个示例项目: https: //github.com/jerbeers/DemoLocalNotification

如果您构建并运行,点击按钮,您将在 3 秒后看到本地通知。如果您停止、构建并再次运行,即使应用程序正在运行,我也会看到本地通知。