userNotificationCenter:willPresentNotification:withCompletionHandler: 的预期行为是什么 当应用程序的通知设置在设备级别关闭时?我总是假设如果设置关闭,则不会调用回调,但我在我的应用程序中观察到,即使设备设置关闭,此回调也会遇到断点。 Apple 文档没有提及任何有关预期行为的信息,因此想知道这里是否有人知道预期行为是什么,或者这是否是 iOS 错误。
谢谢!
这是预期的行为,也是您应该期待的。让我们像这样把它分开吧。
用户表示他们不想看到任何通知证据(警报、横幅、声音、徽章)。但这并不意味着没有通知存在——用户无法进入系统并关闭用户通知中心本身!所以通知中心仍然在运行,通知,qua信号,仍然有能力到达。
很好,所以用户确实不会去看到任何警报、横幅、声音或徽章。正如我们在上一点中所同意的,所发生的只是通知 qua 信号已经到达。并且您的应用程序恰好位于最前面,因此能够听到通知信号到达的事实。
为什么你的应用程序不应该听到这个消息?您的应用程序不会通过呈现任何通知警报、横幅等来违反用户的意愿;无论如何它都不能这样做。但它仍然可以“响应”通知。没有理由允许用户访问您的应用程序并通过阻止其自己的通知消息到达它来“蹩脚”它,就像没有理由允许用户破坏用户通知中心的操作一样。
您可以使用传递给此方法的 UNNotification 对象的设置属性中提供的 UNNotificationSettings 对象来检查您的应用程序是否允许或拒绝通知。以下是如何使用它的示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let settings = notification.request.content.userInfo["aps"] as? [String: Any]
if let settings = settings,
let alert = settings["alert"] as? [String: Any],
let title = alert["title"] as? String {
// Check if notifications are allowed for your app
if notification.settings.authorizationStatus == .authorized {
// Notifications are allowed, you can choose to display it to the user.
completionHandler([.alert, .sound])
} else {
// Notifications are not allowed, you can handle it in your app accordingly.
// For example, log the notification or update your app's state.
completionHandler([])
}
}
}
在此代码中,如果允许通知,应用程序将使用 .alert 和 .sound 选项向用户显示通知。如果不允许通知,应用程序会选择不显示它,但您仍然可以根据通知内容执行其他操作。