无法更新本地预定的通知内容

Bor*_* Y. 5 ios swift3 usernotifications

在WWDC会话之一中,我获得了用于更新现有通知的代码段。我认为这行不通。尝试更新通知内容。

首先,我请求UNUserNotificationCenter始终有效的待处理通知。然后,我创建新请求以使用现有的唯一标识符更新通知。

有1个新变量content: String

// Got at least one pending notification.
let triggerCopy = request!.trigger as! UNTimeIntervalNotificationTrigger
let interval = triggerCopy.timeInterval
let newTrigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: true)

// Update notificaion conent.
let notificationContent = UNMutableNotificationContent()
notificationContent.title = NSString.localizedUserNotificationString(forKey: "Existing Title", arguments: nil)
notificationContent.body = content
let updateRequest = UNNotificationRequest(identifier: request!.identifier, content: notificationContent, trigger: newTrigger)
UNUserNotificationCenter.current().add(updateRequest, withCompletionHandler: { (error) in
    if error != nil {
        print(" Couldn't update notification \(error!.localizedDescription)")
    }
})
Run Code Online (Sandbox Code Playgroud)

我无法捕获错误。问题在于通知内容主体 不会更改。

更新。

我还尝试更改具有不同重复间隔的触发器。它不起作用,将以创建时的原始间隔重复进行通知。

更新2。

阅读克里斯的答案,尝试使用第一个选项。

let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { (requests) in
    for request in requests {
        if request.identifier == notificationIdentifier {
            // Got at least one pending notification,
            // update its content.
            let notificationContent = UNMutableNotificationContent()
            notificationContent.title = NSString.localizedUserNotificationString(forKey: "new title", arguments: nil)
            notificationContent.body = "new body"
            request.content = notificationContent // ?? request.content is read only.
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

如您所见,我无法修改原始请求。

更新3。

有了第二个“删除第一个”选项。注意到调用removePendingNotificationRequests和调度之后,还给了我旧的通知版本。我必须在removePendingNotificationRequests和之间添加1秒的延迟center.add(request)

将克里斯的回答标记为已接受,但可以随时分享更好的选择。

Chr*_*ein 4

问题是您没有修改现有通知,而是添加具有重复标识符的新通知。

让我们首先解决重复问题,重复通知不显示的原因是标识符不唯一。来自文档

(如果标识符不唯一,则不会发送通知)。

你有两个选择。您可以 1) 修改现有通知,或 2) 删除它并添加新通知。

对于 1,您已经有了请求,无需从中提取触发器和标识符,只需将 request.content 替换为更新的 notificationContent 即可。

对于 2,您只需要在 Add 之前添加一行:

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [request!.identifier])
Run Code Online (Sandbox Code Playgroud)

  • @ChrisAllwein,您好,您的答案确实有道理,但是我无法真正更新请求,因为它的属性是只读的。我已使用您在选项 1 中建议的代码更新了我的问题。 (2认同)