在SDWebImage基础上添加UIImageView扩展使其可以缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import SDWebImage

extension UIImageView {
// 设置并缓存image
func sd_setImageAndCached(with urlString: String, placeholderImage: UIImage? = nil) {
self.image = placeholderImage
self.sd_cancelImageLoadOperation(withKey: "UIImageViewImageLoad")
let operation =
UIImage.getImageWithURLString(
urlString,
showLoadingView: false,
completion: { [weak self] (image) in
let img = image ?? placeholderImage
self?.image = img
}
)

if operation != nil {
self.sd_setImageLoadOperation(operation, forKey: "UIImageViewImageLoad")
}
}
}


extension UIImage {

// 使用URLString获取一张图片
@discardableResult
class func getImageWithURLString(_ urlString: String, showLoadingView: Bool = false, completion: @escaping (_ image: UIImage?) -> ()) -> SDWebImageOperation? {
if let url = URL.init(string: urlString) {
if SDWebImageManager.shared().cachedImageExists(for: url) {
let key = SDWebImageManager.shared().cacheKey(for: url)
let image = SDImageCache.shared().imageFromDiskCache(forKey:key)
completion(image)
return nil
} else if SDWebImageManager.shared().diskImageExists(for: url){
let key = SDWebImageManager.shared().cacheKey(for: url)
let image = SDImageCache.shared().imageFromDiskCache(forKey: key)
completion(image)
return nil
} else {
if showLoadingView {
PAMBManager.sharedInstance.showLoading(view: nil)
}
let operation =
SDWebImageManager.shared().downloadImage(
with: url,
options: SDWebImageOptions.init(rawValue: 0),
progress: nil,
completed: { [showLoadingView, completion] (image, error, cacheType, finished, imageURL) in
if showLoadingView {
PAMBManager.sharedInstance.hideAlert(view: nil)
}
completion(image)
}
)
return operation
}
} else {
completion(nil)
return nil
}
}
}
0%