Repository navigation
Expand file tree
/
Copy pathDKAsyncImageView.swift
More file actions
234 lines (196 loc) · 9.03 KB
/
Copy pathDKAsyncImageView.swift
File metadata and controls
234 lines (196 loc) · 9.03 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//
// DKAsyncImageView.swift
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 David Kopec
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Cocoa
/// A Swift subclass of NSImageView for loading remote images asynchronously.
open class DKAsyncImageView: NSImageView, URLSessionDelegate, URLSessionDownloadDelegate {
fileprivate var imageURLDownloadTask: URLSessionDownloadTask?
fileprivate var networkSession: Foundation.URLSession?
fileprivate var imageDownloadData: Data?
fileprivate var errorImage: NSImage?
fileprivate var spinningWheel: NSProgressIndicator?
fileprivate var trackingArea: NSTrackingArea?
var isLoadingImage: Bool = false
var userDidCancel: Bool = false
var didFailLoadingImage: Bool = false
fileprivate var toolTipWhileLoading: String?
fileprivate var toolTipWhenFinished: String?
fileprivate var toolTipWhenFinishedWithError: String?
deinit {
cancelDownload()
}
/// Grab an image form a URL and asynchronously load it into the image view
///
/// - parameter url: A String representing the URL of the image.
/// - parameter placeHolderImage: an optional NSImage to temporarily display while the image is downloading
/// - parameter errorImage: an optional NSImage that displays if the download fails.
/// - parameter usesSpinningWheel: A Bool that determines whether or not a spinning wheel indicator displays during download
open func downloadImageFromURL(_ url: String, placeHolderImage:NSImage? = nil, errorImage:NSImage? = nil, usesSpinningWheel: Bool = false) {
cancelDownload()
isLoadingImage = true
didFailLoadingImage = false
userDidCancel = false
image = placeHolderImage
self.errorImage = errorImage
imageDownloadData = NSMutableData() as Data
guard let URL = URL(string: url) else {
isLoadingImage = false
NSLog("Error: malformed URL passed to downloadImageFromURL")
return
}
networkSession = Foundation.URLSession.init(configuration:URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
imageURLDownloadTask = networkSession!.downloadTask(with: URL)
imageURLDownloadTask?.resume()
if usesSpinningWheel {
if self.frame.size.height >= 64 && self.frame.size.width >= 64 {
spinningWheel = NSProgressIndicator()
if let spinningWheel = spinningWheel {
addSubview(spinningWheel)
spinningWheel.style = NSProgressIndicatorStyle.spinningStyle
spinningWheel.isDisplayedWhenStopped = false
spinningWheel.frame = NSMakeRect(self.frame.size.width * 0.5 - 16, self.frame.size.height * 0.5 - 16, 32, 32)
spinningWheel.controlSize = NSControlSize.regular
spinningWheel.startAnimation(self)
}
} else if (self.frame.size.height < 64 && self.frame.size.height >= 16) && (self.frame.size.width < 64 && self.frame.size.width >= 16) {
spinningWheel = NSProgressIndicator()
if let spinningWheel = spinningWheel {
addSubview(spinningWheel)
spinningWheel.style = NSProgressIndicatorStyle.spinningStyle
spinningWheel.isDisplayedWhenStopped = false
spinningWheel.frame = NSMakeRect(self.frame.size.width * 0.5 - 8, self.frame.size.height * 0.5 - 8, 16, 16)
spinningWheel.controlSize = NSControlSize.small
spinningWheel.startAnimation(self)
}
}
}
}
/// Cancel the download
open func cancelDownload() {
userDidCancel = true
isLoadingImage = false
didFailLoadingImage = false
spinningWheel?.stopAnimation(self)
spinningWheel?.removeFromSuperview()
networkSession?.invalidateAndCancel()
imageURLDownloadTask = nil
imageDownloadData = nil
errorImage = nil
image = nil
}
fileprivate func failureReset() {
isLoadingImage = false
didFailLoadingImage = true
userDidCancel = false
spinningWheel?.stopAnimation(self)
spinningWheel?.removeFromSuperview()
imageDownloadData = nil
imageURLDownloadTask = nil
image = errorImage
errorImage = nil
}
//MARK: NSURLSessionDownloadTask Delegate
open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
imageDownloadData = try? Data.init(contentsOf: location)
}
//MARK: NSURLSessionTask Delegate
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard error == nil else {
Swift.print(error!.localizedDescription)
failureReset()
return;
}
didFailLoadingImage = false
userDidCancel = false
guard let data = imageDownloadData else {
Swift.print("Image data not downloaded correctly.")
failureReset()
return;
}
guard let img: NSImage = NSImage(data: data) else {
Swift.print("Error forming image from data.")
failureReset()
return;
}
image = img
isLoadingImage = false
spinningWheel?.stopAnimation(self)
spinningWheel?.removeFromSuperview()
imageDownloadData = nil
imageURLDownloadTask = nil
errorImage = nil
}
//MARK: Tooltips
/// Set tooltips for loading, finished, and error states
///
/// - parameter ttip1: The tool tip to show while loading
/// - parameter whenFinished: The tool tip that shows after the image downloaded.
/// - parameter andWhenFinishedwithError: The tool tip that shows when an error occurs.
open func setToolTipWhileLoading(_ ttip1: String?, whenFinished ttip2:String?, andWhenFinishedWithError ttip3: String?) {
toolTipWhileLoading = ttip1
toolTipWhenFinished = ttip2
toolTipWhenFinishedWithError = ttip3
}
/// Remove all tooltips
open func deleteToolTips() {
toolTip = nil
toolTipWhileLoading = nil
toolTipWhenFinished = nil
toolTipWhenFinishedWithError = nil
}
override open func mouseEntered(with theEvent: NSEvent) {
if !userDidCancel { // the user didn't cancel the operation so show the tooltips
if isLoadingImage {
if let toolTipWhileLoading = toolTipWhileLoading {
toolTip = toolTipWhileLoading
} else {
toolTip = nil
}
}
else if didFailLoadingImage { //connection failed
if let toolTipWhenFinishedWithError = toolTipWhenFinishedWithError {
toolTip = toolTipWhenFinishedWithError
} else {
toolTip = nil
}
}
else if !isLoadingImage { // it's not loading image
if let toolTipWhenFinished = toolTipWhenFinished {
toolTip = toolTipWhenFinished
} else {
toolTip = nil
}
}
}
}
override open func updateTrackingAreas() {
if let trackingArea = trackingArea {
removeTrackingArea(trackingArea)
}
let opts: NSTrackingAreaOptions = NSTrackingAreaOptions(rawValue: NSTrackingAreaOptions.mouseEnteredAndExited.rawValue | NSTrackingAreaOptions.activeAlways.rawValue)
trackingArea = NSTrackingArea(rect: self.bounds, options: opts, owner: self, userInfo: nil)
if let trackingArea = trackingArea {
self.addTrackingArea(trackingArea)
}
}
}