2024-05-29 15:14:12 +08:00

63 lines
2.2 KiB
Swift

//
// ImageDownloader.swift
// NotificationServiceExtension
//
// Created by huangfeng on 2024/5/29.
// Copyright © 2024 Fin. All rights reserved.
//
import Foundation
import Kingfisher
class ImageDownloader {
///
/// - Parameters:
/// - cache: 使
/// - data: Data
/// - key: Key
class func storeImage(cache: ImageCache, data: Data, key: String) async {
return await withCheckedContinuation { continuation in
cache.storeToDisk(data, forKey: key, expiration: StorageExpiration.never) { _ in
continuation.resume()
}
}
}
/// 使 Kingfisher.ImageDownloader
/// - Parameter url: URL
/// - Returns: Result
class func downloadImage(url: URL) async -> Result<ImageLoadingResult, KingfisherError> {
return await withCheckedContinuation { continuation in
Kingfisher.ImageDownloader.default.downloadImage(with: url, options: nil) { result in
continuation.resume(returning: result)
}
}
}
///
/// - Parameter imageUrl: URL
/// - Returns: ` File URL`
class func downloadImage(_ imageUrl: String) async -> String? {
guard let groupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bark"),
let cache = try? ImageCache(name: "shared", cacheDirectoryURL: groupUrl),
let imageResource = URL(string: imageUrl)
else {
return nil
}
//
if cache.diskStorage.isCached(forKey: imageResource.cacheKey) {
return cache.cachePath(forKey: imageResource.cacheKey)
}
//
guard let result = try? await downloadImage(url: imageResource).get() else {
return nil
}
//
await storeImage(cache: cache, data: result.originalData, key: imageResource.cacheKey)
return cache.cachePath(forKey: imageResource.cacheKey)
}
}