ImageDownloader.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // ImageDownloader.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 Kingfisher
  10. class ImageDownloader {
  11. /// 保存图片到缓存中
  12. /// - Parameters:
  13. /// - cache: 使用的缓存
  14. /// - data: 图片 Data 数据
  15. /// - key: 缓存 Key
  16. class func storeImage(cache: ImageCache, data: Data, key: String) async {
  17. return await withCheckedContinuation { continuation in
  18. cache.storeToDisk(data, forKey: key, expiration: StorageExpiration.never) { _ in
  19. continuation.resume()
  20. }
  21. }
  22. }
  23. /// 使用 Kingfisher.ImageDownloader 下载图片
  24. /// - Parameter url: 下载的图片URL
  25. /// - Returns: 返回 Result
  26. class func downloadImage(url: URL) async -> Result<ImageLoadingResult, KingfisherError> {
  27. return await withCheckedContinuation { continuation in
  28. Kingfisher.ImageDownloader.default.downloadImage(with: url, options: nil) { result in
  29. continuation.resume(returning: result)
  30. }
  31. }
  32. }
  33. /// 下载推送图片
  34. /// - Parameter imageUrl: 图片URL字符串
  35. /// - Returns: 保存在本地中的`图片 File URL`
  36. class func downloadImage(_ imageUrl: String) async -> String? {
  37. guard let groupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bark"),
  38. let cache = try? ImageCache(name: "shared", cacheDirectoryURL: groupUrl),
  39. let imageResource = URL(string: imageUrl)
  40. else {
  41. return nil
  42. }
  43. // 先查看图片缓存
  44. if cache.diskStorage.isCached(forKey: imageResource.cacheKey) {
  45. return cache.cachePath(forKey: imageResource.cacheKey)
  46. }
  47. // 下载图片
  48. guard let result = try? await downloadImage(url: imageResource).get() else {
  49. return nil
  50. }
  51. // 缓存图片
  52. await storeImage(cache: cache, data: result.originalData, key: imageResource.cacheKey)
  53. return cache.cachePath(forKey: imageResource.cacheKey)
  54. }
  55. }