NotificationService.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // NotificationService.swift
  3. // NotificationServiceExtension
  4. //
  5. // Created by huangfeng on 2018/12/17.
  6. // Copyright © 2018 Fin. All rights reserved.
  7. //
  8. import UserNotifications
  9. class NotificationService: UNNotificationServiceExtension {
  10. /// 当前正在运行的 Processor
  11. var currentNotificationProcessor: NotificationContentProcessor? = nil
  12. /// 当前 ContentHandler,主要用来 serviceExtensionTimeWillExpire 时,传递给 Processor 用来交付推送。
  13. var currentContentHandler: ((UNNotificationContent) -> Void)? = nil
  14. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
  15. Task {
  16. guard var bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
  17. contentHandler(request.content)
  18. return
  19. }
  20. self.currentContentHandler = contentHandler
  21. // 所有的 processor, 按顺序从上往下对推送进行处理
  22. // ciphertext 需要放在最前面,有可能所有的推送数据都在密文里
  23. // call 需要放在最后面,因为这个 Processor 不会主动退出, 会一直等到 ServiceExtension 被终止
  24. let processors: [NotificationContentProcessorItem] = [
  25. .ciphertext,
  26. .level,
  27. .badge,
  28. .autoCopy,
  29. .archive,
  30. .setIcon,
  31. .setImage,
  32. .call
  33. ]
  34. // 各个 processor 依次对推送进行处理
  35. for processor in processors.map({ $0.processor }) {
  36. do {
  37. self.currentNotificationProcessor = processor
  38. bestAttemptContent = try await processor.process(identifier: request.identifier, content: bestAttemptContent)
  39. } catch NotificationContentProcessorError.error(let content) {
  40. contentHandler(content)
  41. return
  42. }
  43. }
  44. // 处理完后交付推送
  45. contentHandler(bestAttemptContent)
  46. }
  47. }
  48. override func serviceExtensionTimeWillExpire() {
  49. super.serviceExtensionTimeWillExpire()
  50. if let handler = self.currentContentHandler {
  51. self.currentNotificationProcessor?.serviceExtensionTimeWillExpire(contentHandler: handler)
  52. }
  53. }
  54. }