在getTimline方法中,下載好所有圖片
調(diào)用
Image(uiImage: WidgetImageLoader.shareLoader.getImage(itemModel.image, UIImage()))
.resizable()
.scaledToFit()
.cornerRadius(16)
.frame(width: 44, height: 44)
創(chuàng)建.Swift文件WidgetImageLoader.swift
import Foundation
import SwiftUI
enum WidgetError: Error {
case netError //網(wǎng)絡(luò)請(qǐng)求出錯(cuò)
case dataError //數(shù)據(jù)解析錯(cuò)誤
}
/*
由于不支持異步加載圖片
所以暫時(shí)在網(wǎng)絡(luò)請(qǐng)求好之后聂渊,直接下載好全部圖片
使用NSCache暫存圖片
*/
class WidgetImageLoader {
static var shareLoader = WidgetImageLoader()
private var cache = NSCache<NSURL, UIImage>()
/// 下載單張圖片
/// - Parameters:
/// - imageUrl: 圖片URL
/// - completion: 成功的回調(diào)
func downLoadImage(imageUrl: String?,completion: @escaping (Result<UIImage, WidgetError>) -> Void) {
if let imageUrl = imageUrl {
if let cacheImage = self.cache.object(forKey: NSURL(string: imageUrl)!) {
completion(.success(cacheImage))
} else {
URLSession.shared.dataTask(with: URL(string: imageUrl)!) { (data, response, error) in
if let data = data,
let image = UIImage(data: data) {
self.cache.setObject(image, forKey: NSURL(string: imageUrl)!)
completion(.success(image))
} else {
completion(.failure(WidgetError.netError))
}
}.resume()
}
} else {
completion(.failure(WidgetError.dataError))
}
}
/// 批量下載圖片
/// - Parameters:
/// - imageAry: 圖片數(shù)組集合
/// - placeHolder: 占位圖,可傳可不傳
/// - completion: 成功回調(diào)
func downLoadImage(imageAry:[String],placeHolder:UIImage?,completion: @escaping (Result<[UIImage], WidgetError>) -> Void) {
let group:DispatchGroup = DispatchGroup()
var array = [UIImage]()
for image in imageAry {
group.enter()
self.downLoadImage(imageUrl: image) { result in
let image : UIImage
if case .success(let response) = result {
image = response
} else {
image = placeHolder ?? UIImage()
}
array.append(image)
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
completion(.success(array))
}
}
/// 獲取image
/// - Parameters:
/// - imageUrl: 圖片地址
/// - placeHolderImage: 占位圖,請(qǐng)盡量傳入
/// - Returns: 返回結(jié)果
func getImage(_ imageUrl:String, _ placeHolderImage:UIImage?) -> UIImage {
if let cacheImage = self.cache.object(forKey: NSURL(string: imageUrl)!) {
return cacheImage
} else {
if let cacheImag = placeHolderImage {
return cacheImag
} else {
return UIImage()
}
}
}
}