iOS - 通过本地推送通知触发通知服务扩展?

iOS - Trigger Notification Service Extension through Local Push Notification?

Is it possible to trigger Notification Service Extension through Local Push Notification?

我的代码片段

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()

// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default

let aps = ["mutable-content": 1]
let dict = ["aps": aps, "some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

发帖前请阅读documentation。第一行声明:

A UNNotificationServiceExtension object provides the entry point for a Notification Service app extension, which lets you customize the content of a remote notification before it is delivered to the user.

否,无法通过推送通知触发通知服务扩展。

原因:Service extension lets you customize the content of a remote notification before it is delivered to the user. e.g decrypt the message or download the attachments

但我个人认为在服务扩展中下载通知内容附件是没有意义的,因为您总是可以在安排之前下载附件。例如

    // Download attachment asynchronously 
    downloadAttachments(data: data) { attachments in
      UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    let content = UNMutableNotificationContent()
    // Add downloaded attachment here
    content.attachments = attachments

    // Adding title,subtitle,body & badge
    content.title = "title"
    content.body = "body"
    content.sound = UNNotificationSound.default

    // No need of adding mutable content here
    let dict = ["some-key": "some-value"] as [AnyHashable : Any]
    content.userInfo = dict

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

如果您有不同的用例,请告诉我。