-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwiftyImageDownloader.swift
85 lines (77 loc) · 3.22 KB
/
SwiftyImageDownloader.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//
// SwiftyImageDownloader.swift
// SwiftyImage
//
// Created by Sharad on 23/10/20.
//
import UIKit
class SwiftyImageDownloader: UIImageView {
let imageFolderName = "SwiftyImage"
func downloadImageFrom(url: URL) {
let queue = DispatchQueue(label: "ImageDownloader", qos: .background, attributes: .concurrent, autoreleaseFrequency: .workItem, target: .none)
queue.async { [weak self] in
guard let strongSelf = self else {return}
let fileName = url.absoluteString.fileName()
if strongSelf.checkIfFileExist(fileName), let imageData = strongSelf.getSavedImageData(fileName) {
DispatchQueue.main.async {
strongSelf.image = UIImage(data: imageData)
}
} else {
URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let strongSelf = self, let imageData = data, error == nil, let downloadedImage = UIImage(data: imageData) else { return }
strongSelf.saveImage(fileName, imageData)
DispatchQueue.main.async {
strongSelf.image = downloadedImage
}
}.resume()
}
}
}
private func getSavedImageData(_ fileName: String) -> Data? {
do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent("\(fileName)")
return try Data(contentsOf: savedURL)
} catch {
print ("file error: \(error)")
return nil
}
}
private func saveImage(_ fileName: String, _ imageData: Data) {
do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent("\(fileName)")
try imageData.write(to: savedURL)
} catch {
print ("file error: \(error)")
}
}
private func checkIfFileExist(_ fileName: String) -> Bool {
do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent("\(fileName)")
return FileManager.default.fileExists(atPath: savedURL.path)
} catch {
print ("file error: \(error)")
return false
}
}
}
//Extension to create redable file name by removing special characters from url
extension String {
func fileName() -> String {
return self.replacingOccurrences(of: "[/+.:.-]", with: "", options: .regularExpression, range: nil)
}
}