-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUIImageView+Download.swift
67 lines (48 loc) · 2.25 KB
/
UIImageView+Download.swift
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
65
66
67
//
// UIImageView+Download.swift
//
// Created by Alessio Sardella on 05/06/2019.
// Copyright 2019 Alessio Sardella. All rights reserved.
//
import UIKit
typealias ManageDownloadImageError = (ErrorDownloadImage) -> ()
enum ErrorDownloadImage {
case download
case localSave
}
extension UIImageView {
/**
Lazy load for images. Download images and save them locally, while showing it inside the UIImageView, if still available.
If a local image already exists it will be loaded immediately, then the download will start and the local image will be updated.
- parameter link: link to download remote image
- parameter contentMode: content mode of the UIImageView after download.
- parameter savePath: Path where to save the image locally
*/
func downloadImageFrom(link: URL, contentMode: UIView.ContentMode, savePath: String, manageError: ManageDownloadImageError?) {
if let localImage = UIImage(contentsOfFile: savePath) {
self.image = localImage
self.contentMode = contentMode
self.backgroundColor = .white
}
URLSession.shared.dataTask(with: link, completionHandler: { (data, _, _) -> Void in
DispatchQueue.main.async { [weak self] in
if let imageData = data,
let downloadedImage = UIImage(data: imageData) {
self?.contentMode = contentMode
self?.image = downloadedImage
self?.backgroundColor = .white
DispatchQueue.global(qos: .background).async {
do {
let url = URL(fileURLWithPath: savePath)
try downloadedImage.jpegData(compressionQuality: 1.0)?.write(to: url)
} catch {
manageError?(.localSave)
}
}
}else{
manageError?(.download)
}
}
}).resume()
}
}