-
Notifications
You must be signed in to change notification settings - Fork 10
/
Utilities.swift
216 lines (193 loc) · 7.24 KB
/
Utilities.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//
// Utilities.swift
//
// Created by CS193p Instructor.
// Copyright © 2017 Stanford University. All rights reserved.
//
import UIKit
class ImageFetcher
{
// Public API
// To use, create with the closure you want called when the image is ready.
// Example: let fetcher = ImageFetcher() { // code to execute when fetch is done }
// Your closure is invoked OFF THE MAIN THREAD.
// Then call fetch(url:) with the url you want to fetch.
// And set a backup image in case the fetch fails.
//
// The handler will be called immediately if the fetch succeeds.
// If the fetch fails, the handler will be called if and when the backup image is set.
// The backup can be set at any time (i.e. before, during or after the fetch).
// If the fetch fails and a backup image is never set, the handler will never be called.
// Thus it would sort of be a strange use of this class to not set a backup image
// (because you'd never find out when the fetch failed).
// Note that you must keep a strong pointer to this object until the fetch finishes
// otherwise the result of the fetch will be discarded and the handler never called.
// In other words, keeping a strong pointer to your instance says "I'm still interested in its result."
var backup: UIImage? { didSet { callHandlerIfNeeded() } }
func fetch(_ url: URL) {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
if let data = try? Data(contentsOf: url.imageURL) {
if self != nil {
// yes, it's ok to create a UIImage off the main thread
if let image = UIImage(data: data) {
self?.handler(url, image)
} else {
self?.fetchFailed = true
}
} else {
print("ImageFetcher: fetch returned but I've left the heap -- ignoring result.")
}
} else {
self?.fetchFailed = true
}
}
}
init(handler: @escaping (URL, UIImage) -> Void) {
self.handler = handler
}
init(fetch url: URL, handler: @escaping (URL, UIImage) -> Void) {
self.handler = handler
fetch(url)
}
// Private Implementation
private let handler: (URL, UIImage) -> Void
private var fetchFailed = false { didSet { callHandlerIfNeeded() } }
private func callHandlerIfNeeded() {
if fetchFailed, let image = backup, let url = image.storeLocallyAsJPEG(named: String(Date().timeIntervalSinceReferenceDate)) {
handler(url, image)
}
}
}
extension URL {
var imageURL: URL {
if let url = UIImage.urlToStoreLocallyAsJPEG(named: self.path) {
// this was created using UIImage.storeLocallyAsJPEG
return url
} else {
// check to see if there is an embedded imgurl reference
for query in query?.components(separatedBy: "&") ?? [] {
let queryComponents = query.components(separatedBy: "=")
if queryComponents.count == 2 {
if queryComponents[0] == "imgurl", let url = URL(string: queryComponents[1].removingPercentEncoding ?? "") {
return url
}
}
}
return self.baseURL ?? self
}
}
}
extension UIImage
{
private static let localImagesDirectory = "UIImage.storeLocallyAsJPEG"
static func urlToStoreLocallyAsJPEG(named: String) -> URL? {
var name = named
let pathComponents = named.components(separatedBy: "/")
if pathComponents.count > 1 {
if pathComponents[pathComponents.count-2] == localImagesDirectory {
name = pathComponents.last!
} else {
return nil
}
}
if var url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
url = url.appendingPathComponent(localImagesDirectory)
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
url = url.appendingPathComponent(name)
if url.pathExtension != "jpg" {
url = url.appendingPathExtension("jpg")
}
return url
} catch let error {
print("UIImage.urlToStoreLocallyAsJPEG \(error)")
}
}
return nil
}
func storeLocallyAsJPEG(named name: String) -> URL? {
if let imageData = UIImageJPEGRepresentation(self, 1.0) {
if let url = UIImage.urlToStoreLocallyAsJPEG(named: name) {
do {
try imageData.write(to: url)
return url
} catch let error {
print("UIImage.storeLocallyAsJPEG \(error)")
}
}
}
return nil
}
}
extension String {
func madeUnique(withRespectTo otherStrings: [String]) -> String {
var possiblyUnique = self
var uniqueNumber = 1
while otherStrings.contains(possiblyUnique) {
possiblyUnique = self + " \(uniqueNumber)"
uniqueNumber += 1
}
return possiblyUnique
}
}
extension Array where Element: Equatable {
var uniquified: [Element] {
var elements = [Element]()
forEach { if !elements.contains($0) { elements.append($0) } }
return elements
}
}
extension NSAttributedString {
func withFontScaled(by factor: CGFloat) -> NSAttributedString {
let mutable = NSMutableAttributedString(attributedString: self)
mutable.setFont(mutable.font?.scaled(by: factor))
return mutable
}
var font: UIFont? {
get { return attribute(.font, at: 0, effectiveRange: nil) as? UIFont }
}
}
extension String {
func attributedString(withTextStyle style: UIFontTextStyle, ofSize size: CGFloat) -> NSAttributedString {
let font = UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont.preferredFont(forTextStyle: .body).withSize(size))
return NSAttributedString(string: self, attributes: [.font:font])
}
}
extension NSMutableAttributedString {
func setFont(_ newValue: UIFont?) {
if newValue != nil { addAttributes([.font:newValue!], range: NSMakeRange(0, length)) }
}
}
extension UIFont {
func scaled(by factor: CGFloat) -> UIFont { return withSize(pointSize * factor) }
}
extension UILabel {
func stretchToFit() {
let oldCenter = center
sizeToFit()
center = oldCenter
}
}
extension CGPoint {
func offset(by delta: CGPoint) -> CGPoint {
return CGPoint(x: x + delta.x, y: y + delta.y)
}
}
extension UIViewController {
var contents: UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController ?? navcon
} else {
return self
}
}
}
extension UIView {
var snapshot: UIImage? {
UIGraphicsBeginImageContext(bounds.size)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}