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

时间:2019-12-06 10:43:41

标签: ios swift push-notification extension-methods local

  

是否可以通过本地推送通知触发通知服务扩展

我的代码段

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)

2 个答案:

答案 0 :(得分:0)

请在发布前阅读documentation。第一行指出:

  

UNNotificationServiceExtension对象为Notification Service应用程序扩展提供了入口点,可让您自定义远程通知的内容,然后将其交付给用户。

答案 1 :(得分:0)

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

原因: 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)
    }

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