-
Notifications
You must be signed in to change notification settings - Fork 0
/
URLImageView.swift
113 lines (78 loc) · 2.95 KB
/
URLImageView.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//
// URLImage.swift
//
// Created by Sasa Blagojevic on 8/11/17.
// Copyright © 2017 Sasa Blagojevic. All rights reserved.
//
import UIKit
class URLImageView: UIImageView {
let cache: NSCache<NSString, UIImage>
var request: URLSessionDataTask?
var placeholder: UIImage?
var fadeIn: Bool = true
var fadeDuration: Double = 0.3
var startAlpha: CGFloat = 0.0
fileprivate var callable: (() -> Void)?
init() {
cache = NSCache()
super.init(image: nil)
}
init(url: String, placeholder: UIImage? = nil) {
cache = NSCache()
self.placeholder = placeholder
super.init(image: placeholder)
guard let link = URL(string: url) else { return }
from(url: link)
}
required init?(coder aDecoder: NSCoder) {
cache = NSCache()
super.init(coder: aDecoder)
}
public func setPlaceholderImage(_ img: UIImage) {
placeholder = img
}
public func from(url: URL?, completionHandler: (() -> Void)? = nil) -> Void {
if let _: URL = url {
if fadeIn {
alpha = 0.0
}
if let fromCache: UIImage = cache.object(forKey: url!.absoluteString as NSString) {
image = fromCache
if fadeIn {
UIView.animate(withDuration: self.fadeDuration, animations: {
self.alpha = 1.0
})
}
callable?()
return
}
if let _ = placeholder {
image = placeholder
}
let session: URLSession = URLSession(configuration: URLSessionConfiguration.default)
request = session.dataTask(with: url!) { data, response, error in
guard error == nil else { return }
DispatchQueue.main.async {
self.image = UIImage(data: data!)
if self.fadeIn {
UIView.animate(withDuration: self.fadeDuration, animations: {
self.alpha = 1.0
})
}
if let _ = self.image {
self.cache.setObject(self.image!, forKey: url!.absoluteString as NSString)
}
if let callable = completionHandler {
callable()
} else {
self.callable?()
}
}
}
request?.resume()
}
}
public func register(completionHandler: @escaping () -> Void) {
callable = completionHandler
}
}