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

时间:2017-07-11 11:56:21

标签: ios swift3 usernotifications

在其中一个WWDC会话中,我获得了用于更新现有通知的代码段。我认为它不起作用。尝试更新通知内容。

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

有一个新变量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)")
    }
})

我无法发现错误。问题是通知内容正文不会改变。

更新

我也尝试用不同的重复间隔来改变触发器。它不起作用,通过使用相同的原始间隔重复通知。

更新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.
        }
    }
})

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

更新3。

选择第二个“先删除”选项。注意到调用removePendingNotificationRequests并安排在之后,仍然会给我旧的通知版本。在调用removePendingNotificationRequestscenter.add(request)之间,我不得不加1秒延迟。

标记克里斯的回答被接受但随意分享更好的选择。

2 个答案:

答案 0 :(得分:2)

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

让我们首先处理重复的问题,这个重复通知未显示的原因是因为标识符不是唯一的。来自docs

  

(如果标识符不唯一,则不传递通知)。

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

对于1,您已经有了请求,而不是将触发器和标识符拉出来,只需将request.content替换为更新的notificationContent。

对于2,您只需在Add:

之前添加一行
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [request!.identifier])

答案 1 :(得分:0)

我请求允许通知后

我直接从我的viewDidLoad触发通知,但也触发另一个具有相同标识符的通知。最后,updatedBody / updatedTitle显示出来。

import UIKit
import UserNotifications

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let content = UNMutableNotificationContent()
        content.title = "Scheduled Task"
        content.body = "dumbBody"
        content.badge = 1
        content.sound = UNNotificationSound.default()
        content.categoryIdentifier = "alertCategory"

        UNUserNotificationCenter.current().delegate = self

        //Setting time for notification trigger
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 3.0, repeats: false)
        let request = UNNotificationRequest(identifier:"myIdentifier", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: {_ in print(" was registered")})

        updateNotification()
    }

我的更新功能

    func updateNotification(){

        let center = UNUserNotificationCenter.current()
        var request : UNNotificationRequest?

        center.getPendingNotificationRequests{ notifications in
            for notificationRequest in notifications{
                if notificationRequest.identifier == "myIdentifier"{
                    request = notificationRequest
                    center.removeAllPendingNotificationRequests() // Removing this line or keeping it makes NO difference
                }

            }

            let newTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5.0, repeats: false)

            // Update notificaion conent.
            let notificationContent = UNMutableNotificationContent()
            notificationContent.title = "UpdatedTitle"

            notificationContent.body = "updatedBody"
            let updateRequest = UNNotificationRequest(identifier: request!.identifier, content: notificationContent, trigger: newTrigger)
            UNUserNotificationCenter.current().add(updateRequest, withCompletionHandler: { (error) in
                print("successfully updated")
                if error != nil {
                    print(" Couldn't update notification \(error!.localizedDescription)")
                }
            })
        }

    }

}

在上面的代码段中:删除center.removeAllPendingNotificationRequests()没有任何区别。我仍然会收到updatedNotification。

用于处理来电通知

extension ViewController:UNUserNotificationCenterDelegate{      

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    print("original identifier was : \(response.notification.request.identifier)")
    print("original body was : \(response.notification.request.content.body)")
    print("Tapped in notification")

    switch response.actionIdentifier {
    default:
        print("some action was clicked")
    }
}

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        print("Notification being triggered")
        completionHandler( [.alert,.sound,.badge])

    }
}