ImageProcessor.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. //
  2. // ImageProcessor.swift
  3. // NotificationServiceExtension
  4. //
  5. // Created by huangfeng on 2024/5/29.
  6. // Copyright © 2024 Fin. All rights reserved.
  7. //
  8. import Foundation
  9. import MobileCoreServices
  10. class ImageProcessor: NotificationContentProcessor {
  11. func process(identifier: String, content bestAttemptContent: UNMutableNotificationContent) async throws -> UNMutableNotificationContent {
  12. let userInfo = bestAttemptContent.userInfo
  13. guard let imageUrl = userInfo["image"] as? String,
  14. let imageFileUrl = await ImageDownloader.downloadImage(imageUrl)
  15. else {
  16. return bestAttemptContent
  17. }
  18. let copyDestUrl = URL(fileURLWithPath: imageFileUrl).appendingPathExtension(".tmp")
  19. // 将图片缓存复制一份,推送使用完后会自动删除,但图片缓存需要留着以后在历史记录里查看
  20. try? FileManager.default.copyItem(
  21. at: URL(fileURLWithPath: imageFileUrl),
  22. to: copyDestUrl
  23. )
  24. if let attachment = try? UNNotificationAttachment(
  25. identifier: "image",
  26. url: copyDestUrl,
  27. options: [UNNotificationAttachmentOptionsTypeHintKey: kUTTypePNG]
  28. ) {
  29. bestAttemptContent.attachments = [attachment]
  30. }
  31. return bestAttemptContent
  32. }
  33. }