当我第一次运行我的应用程序时,模拟器能够在应用程序位于前台时显示通知。
当我重新启动应用程序时didReceive notification:
(即来自iOS 9的通知方法)被调用而不是willPresent notification
(即来自iOS 10的通知方法),并且当应用程序位于前台时不会显示任何通知。但是,如果应用程序位于后台,则会显示通知。
此question或此question都未提供此问题的解决方案。
我使用此代码获得通知授权:
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
}
我已经实施了willPresent通知方法:
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) completionHandler(UNNotificationPresentationOptions.alert)
}
以下是我创建通知的方式:
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)
问题简而言之:如何在第一次运行应用程序后应用程序处于前台时确保应用程序能够显示通知?
提前致谢。
答案 0 :(得分:1)
尝试在requestAuthorization
完成块之外设置委托。它可能发生的时间比你想要的要晚。
我在这里添加了一个示例项目:https://github.com/jerbeers/DemoLocalNotification
如果您构建并运行,请点击按钮,3秒后您将看到本地通知。如果您停止,构建并再次运行,即使应用程序正在运行,我也会看到本地通知。