距离提出这个问题已有 10 年,还有 17 天。现在,您可以,因为 iOS 10.0`。 ?
我刚刚给how to get the userInfo in other delegate methods写了一个答案。在您的具体情况下,您希望实现userNotificationCenter(_:willPresent:withCompletionHandler:)。
使用notification.request.content.userInfo 在该委托方法中获取userInfo 字典。如果您在传递给 APNs 的 data 有效负载中设置了诸如 foregroundNotification: true 之类的键/值,您的设备可以在此处看到。
你所要做的就是:
let userInfo = notification.request.content.userInfo
if let foregroundNotification = userInfo["foregroundNotification"] as? Bool, foregroundNotification == true {
completionHandler([.banner])
}
更高级的处理(声音,支持 iOS 10+,包括弃用)
请记住,alert 在 iOS 14 中已被弃用,您可能需要添加 iOS 版本检查、声音、列表。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
var options: UNNotificationPresentationOptions = []
let userInfo = notification.request.content.userInfo
if let foregroundSound = userInfo["foregroundSound"] as? Bool, foregroundSound == true {
options.insert(.sound)
}
if let foregroundBadge = userInfo["foregroundBadge"] as? Bool, foregroundBadge == true {
options.insert(.badge)
}
if let foregroundList = userInfo["foregroundList"] as? Bool, foregroundList == true {
if #available(iOS 14.0, *) {
options.insert(.list)
}
}
if let foregroundNotification = userInfo["foregroundNotification"] as? Bool, foregroundNotification == true {
if #available(iOS 14.0, *) {
options.insert(.banner)
} else {
options.insert(.alert)
}
}
completionHandler(options)
}