-
Notifications
You must be signed in to change notification settings - Fork 45
/
MoaDistrib.swift
1227 lines (883 loc) · 31.5 KB
/
MoaDistrib.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Image downloader written in Swift for iOS, tvOS and macOS.
//
// https://github.com/evgenyneu/moa
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// MoaError.swift
//
// ----------------------------
import Foundation
enum MoaError: ErrorProtocol {
/// Incorrect URL is supplied. Error code: 0.
case invalidUrlString
/// Response HTTP status code is not 200. Error code: 1.
case httpStatusCodeIsNot200
/// Response is missing Content-Type http header. Error code: 2.
case missingResponseContentTypeHttpHeader
/// Response Content-Type http header is not an image type. Error code: 3.
case notAnImageContentTypeInResponseHttpHeader
/// Failed to convert response data to UIImage. Error code: 4.
case failedToReadImageData
/// Simulated error used in unit tests. Error code: 5.
case simulatedError
var localizedDescription: String {
let comment = "Moa image downloader error"
switch self {
case .invalidUrlString:
return NSLocalizedString("Invalid URL.", comment: comment)
case .httpStatusCodeIsNot200:
return NSLocalizedString("Response HTTP status code is not 200.", comment: comment)
case .missingResponseContentTypeHttpHeader:
return NSLocalizedString("Response HTTP header is missing content type.", comment: comment)
case .notAnImageContentTypeInResponseHttpHeader:
return NSLocalizedString("Response content type is not an image type. Content type needs to be 'image/jpeg', 'image/pjpeg', 'image/png' or 'image/gif'",
comment: comment)
case .failedToReadImageData:
return NSLocalizedString("Could not convert response data to an image format.",
comment: comment)
case .simulatedError:
return NSLocalizedString("Test error.", comment: comment)
}
}
var code: Int {
return (self as NSError).code
}
var nsError: NSError {
return NSError(
domain: "MoaError",
code: code,
userInfo: [NSLocalizedDescriptionKey: localizedDescription])
}
}
// ----------------------------
//
// MoaHttp.swift
//
// ----------------------------
import Foundation
/**
Shortcut function for creating NSURLSessionDataTask.
*/
struct MoaHttp {
static func createDataTask(_ url: String,
onSuccess: (Data?, HTTPURLResponse)->(),
onError: (NSError?, HTTPURLResponse?)->()) -> URLSessionDataTask? {
if let nsUrl = URL(string: url) {
return createDataTask(nsUrl, onSuccess: onSuccess, onError: onError)
}
// Error converting string to NSURL
onError(MoaError.invalidUrlString.nsError, nil)
return nil
}
private static func createDataTask(_ nsUrl: URL,
onSuccess: (Data?, HTTPURLResponse)->(),
onError: (NSError?, HTTPURLResponse?)->()) -> URLSessionDataTask? {
return MoaHttpSession.session?.dataTask(with: nsUrl) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
if error == nil {
onSuccess(data, httpResponse)
} else {
onError(error, httpResponse)
}
} else {
onError(error, nil)
}
}
}
}
// ----------------------------
//
// MoaHttpImage.swift
//
// ----------------------------
import Foundation
/**
Helper functions for downloading an image and processing the response.
*/
struct MoaHttpImage {
static func createDataTask(_ url: String,
onSuccess: (MoaImage)->(),
onError: (NSError?, HTTPURLResponse?)->()) -> URLSessionDataTask? {
return MoaHttp.createDataTask(url,
onSuccess: { data, response in
self.handleSuccess(data, response: response, onSuccess: onSuccess, onError: onError)
},
onError: onError
)
}
static func handleSuccess(_ data: Data?,
response: HTTPURLResponse,
onSuccess: (MoaImage)->(),
onError: (NSError, HTTPURLResponse?)->()) {
// Show error if response code is not 200
if response.statusCode != 200 {
onError(MoaError.httpStatusCodeIsNot200.nsError, response)
return
}
// Ensure response has the valid MIME type
if let mimeType = response.mimeType {
if !validMimeType(mimeType) {
// Not an image Content-Type http header
let error = MoaError.notAnImageContentTypeInResponseHttpHeader.nsError
onError(error, response)
return
}
} else {
// Missing Content-Type http header
let error = MoaError.missingResponseContentTypeHttpHeader.nsError
onError(error, response)
return
}
if let data = data, image = MoaImage(data: data) {
onSuccess(image)
} else {
// Failed to convert response data to UIImage
let error = MoaError.failedToReadImageData.nsError
onError(error, response)
}
}
private static func validMimeType(_ mimeType: String) -> Bool {
let validMimeTypes = ["image/jpeg", "image/jpg", "image/pjpeg", "image/png", "image/gif"]
return validMimeTypes.contains(mimeType)
}
}
// ----------------------------
//
// MoaHttpImageDownloader.swift
//
// ----------------------------
import Foundation
final class MoaHttpImageDownloader: MoaImageDownloader {
var task: URLSessionDataTask?
var cancelled = false
// When false - the cancel request will not be logged. It is used in order to avoid
// loggin cancel requests after success or error has been received.
var canLogCancel = true
var logger: MoaLoggerCallback?
init(logger: MoaLoggerCallback?) {
self.logger = logger
}
deinit {
cancel()
}
func startDownload(_ url: String, onSuccess: (MoaImage)->(),
onError: (NSError?, HTTPURLResponse?)->()) {
logger?(.requestSent, url, nil, nil)
cancelled = false
canLogCancel = true
task = MoaHttpImage.createDataTask(url,
onSuccess: { [weak self] image in
self?.canLogCancel = false
self?.logger?(.responseSuccess, url, 200, nil)
onSuccess(image)
},
onError: { [weak self] error, response in
self?.canLogCancel = false
if let currentSelf = self where !currentSelf.cancelled {
// Do not report error if task was manually cancelled
self?.logger?(.responseError, url, response?.statusCode, error)
onError(error, response)
}
}
)
task?.resume()
}
func cancel() {
if cancelled { return }
cancelled = true
task?.cancel()
if canLogCancel {
let url = task?.originalRequest?.url?.absoluteString ?? ""
logger?(.requestCancelled, url, nil, nil)
}
}
}
// ----------------------------
//
// MoaHttpSession.swift
//
// ----------------------------
import Foundation
/// Contains functions for managing NSURLSession.
public struct MoaHttpSession {
private static var currentSession: URLSession?
static var session: URLSession? {
get {
if currentSession == nil {
currentSession = createNewSession()
}
return currentSession
}
set {
currentSession = newValue
}
}
private static func createNewSession() -> URLSession {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = Moa.settings.requestTimeoutSeconds
configuration.timeoutIntervalForResource = Moa.settings.requestTimeoutSeconds
configuration.httpMaximumConnectionsPerHost = Moa.settings.maximumSimultaneousDownloads
configuration.requestCachePolicy = Moa.settings.cache.requestCachePolicy
#if os(iOS) || os(tvOS)
// Cache path is a directory name in iOS
let cachePath = Moa.settings.cache.diskPath
#elseif os(OSX)
// Cache path is a disk path in OSX
let cachePath = osxCachePath(Moa.settings.cache.diskPath)
#endif
let cache = URLCache(
memoryCapacity: Moa.settings.cache.memoryCapacityBytes,
diskCapacity: Moa.settings.cache.diskCapacityBytes,
diskPath: cachePath)
configuration.urlCache = cache
return URLSession(configuration: configuration)
}
// Returns the cache path for OSX.
private static func osxCachePath(_ dirName: String) -> String {
var basePath = NSTemporaryDirectory()
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory,
FileManager.SearchPathDomainMask.userDomainMask, true)
if paths.count > 0 {
basePath = paths[0]
}
return (basePath as NSString).appendingPathComponent(dirName)
}
static func cacheSettingsChanged(_ oldSettings: MoaSettingsCache) {
if oldSettings != Moa.settings.cache {
session = nil
}
}
static func settingsChanged(_ oldSettings: MoaSettings) {
if oldSettings != Moa.settings {
session = nil
}
}
/// Calls `finishTasksAndInvalidate` on the current session. A new session will be created for future downloads.
public static func clearSession() {
currentSession?.finishTasksAndInvalidate()
currentSession = nil
}
}
// ----------------------------
//
// ImageView+moa.swift
//
// ----------------------------
import Foundation
private var xoAssociationKey: UInt8 = 0
/**
Image view extension for downloading images.
let imageView = UIImageView()
imageView.moa.url = "http://site.com/image.jpg"
*/
public extension MoaImageView {
/**
Image download extension.
Assign its `url` property to download and show the image in the image view.
// iOS
let imageView = UIImageView()
imageView.moa.url = "http://site.com/image.jpg"
// OS X
let imageView = NSImageView()
imageView.moa.url = "http://site.com/image.jpg"
*/
public var moa: Moa {
get {
if let value = objc_getAssociatedObject(self, &xoAssociationKey) as? Moa {
return value
} else {
let moa = Moa(imageView: self)
objc_setAssociatedObject(self, &xoAssociationKey, moa, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return moa
}
}
set {
objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
// ----------------------------
//
// MoaConsoleLogger.swift
//
// ----------------------------
import Foundation
/**
Logs image download requests, responses and errors to Xcode console for debugging.
Usage:
Moa.logger = MoaConsoleLogger
*/
public func MoaConsoleLogger(_ type: MoaLogType, url: String, statusCode: Int?, error: NSError?) {
let text = MoaLoggerText(type, url: url, statusCode: statusCode, error: error)
print(text)
}
// ----------------------------
//
// MoaLoggerCallback.swift
//
// ----------------------------
import Foundation
/**
A logger closure.
Parameters:
1. Type of the log.
2. URL of the request.
3. Http status code, if applicable.
4. NSError object, if applicable. Read its localizedDescription property to get a human readable error description.
*/
public typealias MoaLoggerCallback = (MoaLogType, String, Int?, NSError?)->()
// ----------------------------
//
// MoaLoggerText.swift
//
// ----------------------------
import Foundation
/**
A helper function that creates a human readable text from log arguments.
Usage:
Moa.logger = { type, url, statusCode, error in
let text = MoaLoggerText(type: type, url: url, statusCode: statusCode, error: error)
// Log log text to your destination
}
For logging into Xcode console you can use MoaConsoleLogger function.
Moa.logger = MoaConsoleLogger
*/
public func MoaLoggerText(_ type: MoaLogType, url: String, statusCode: Int?,
error: NSError?) -> String {
let time = MoaTime.nowLogTime
var text = "[moa] \(time) "
var suffix = ""
switch type {
case .requestSent:
text += "GET "
case .requestCancelled:
text += "Cancelled "
case .responseSuccess:
text += "Received "
case .responseError:
text += "Error "
if let statusCode = statusCode {
text += "\(statusCode) "
}
if let error = error {
suffix = error.localizedDescription
}
}
text += url
if suffix != "" {
text += " \(suffix)"
}
return text
}
// ----------------------------
//
// MoaLogType.swift
//
// ----------------------------
/**
Types of log messages.
*/
public enum MoaLogType: Int{
/// Request is sent
case requestSent
/// Request is cancelled
case requestCancelled
/// Successful response is received
case responseSuccess
/// Response error is received
case responseError
}
// ----------------------------
//
// Moa.swift
//
// ----------------------------
#if os(iOS) || os(tvOS)
import UIKit
public typealias MoaImage = UIImage
public typealias MoaImageView = UIImageView
#elseif os(OSX)
import AppKit
public typealias MoaImage = NSImage
public typealias MoaImageView = NSImageView
#endif
/**
Downloads an image by url.
Setting `moa.url` property of an image view instance starts asynchronous image download using NSURLSession class.
When download is completed the image is automatically shown in the image view.
// iOS
let imageView = UIImageView()
imageView.moa.url = "http://site.com/image.jpg"
// OS X
let imageView = NSImageView()
imageView.moa.url = "http://site.com/image.jpg"
The class can be instantiated and used without an image view:
let moa = Moa()
moa.onSuccessAsync = { image in
return image
}
moa.url = "http://site.com/image.jpg"
*/
public final class Moa {
private var imageDownloader: MoaImageDownloader?
private weak var imageView: MoaImageView?
/// Image download settings.
public static var settings = MoaSettings() {
didSet {
MoaHttpSession.settingsChanged(oldValue)
}
}
/// Supply a callback closure for getting request, response and error logs
public static var logger: MoaLoggerCallback?
/**
Instantiate Moa when used without an image view.
let moa = Moa()
moa.onSuccessAsync = { image in }
moa.url = "http://site.com/image.jpg"
*/
public init() { }
init(imageView: MoaImageView) {
self.imageView = imageView
}
/**
Assign an image URL to start the download.
When download is completed the image is automatically shown in the image view.
imageView.moa.url = "http://mysite.com/image.jpg"
Supply `onSuccessAsync` closure to receive an image when used without an image view:
moa.onSuccessAsync = { image in
return image
}
*/
public var url: String? {
didSet {
cancel()
if let url = url {
startDownload(url)
}
}
}
/**
Cancels image download.
Ongoing image download for the image view is *automatically* cancelled when:
1. Image view is deallocated.
2. New image download is started: `imageView.moa.url = ...`.
Call this method to manually cancel the download.
imageView.moa.cancel()
*/
public func cancel() {
imageDownloader?.cancel()
imageDownloader = nil
}
/**
The closure will be called after download finishes and before the image
is assigned to the image view. The closure is called in the main queue.
The closure returns an image that will be shown in the image view.
Return nil if you do not want the image to be shown.
moa.onSuccess = { image in
// Image is received
return image
}
*/
public var onSuccess: ((MoaImage)->(MoaImage?))?
/**
The closure will be called *asynchronously* after download finishes and before the image
is assigned to the image view.
This is a good place to manipulate the image before it is shown.
The closure returns an image that will be shown in the image view.
Return nil if you do not want the image to be shown.
moa.onSuccessAsync = { image in
// Manipulate the image
return image
}
*/
public var onSuccessAsync: ((MoaImage)->(MoaImage?))?
/**
The closure is called in the main queue if image download fails.
[See Wiki](https://github.com/evgenyneu/moa/wiki/Moa-errors) for the list of possible error codes.
onError = { error, httpUrlResponse in
// Report error
}
*/
public var onError: ((NSError?, HTTPURLResponse?)->())?
/**
The closure is called *asynchronously* if image download fails.
[See Wiki](https://github.com/evgenyneu/moa/wiki/Moa-errors) for the list of possible error codes.
onErrorAsync = { error, httpUrlResponse in
// Report error
}
*/
public var onErrorAsync: ((NSError?, HTTPURLResponse?)->())?
/**
Image that will be used if error occurs. The image will be assigned to the image view. Callbacks `onSuccess` and `onSuccessAsync` will be called with the supplied image. Callbacks `onError` and `onErrorAsync` will also be called.
*/
public var errorImage: MoaImage?
/**
A global error image that will be used if error occurs in any of the image downloads. The image will be assigned to the image view. Callbacks `onSuccess` and `onSuccessAsync` will be called with the supplied image. Callbacks `onError` and `onErrorAsync` will also be called.
*/
public static var errorImage: MoaImage?
private func startDownload(_ url: String) {
cancel()
let simulatedDownloader = MoaSimulator.createDownloader(url)
imageDownloader = simulatedDownloader ?? MoaHttpImageDownloader(logger: Moa.logger)
let simulated = simulatedDownloader != nil
imageDownloader?.startDownload(url,
onSuccess: { [weak self] image in
self?.handleSuccessAsync(image, isSimulated: simulated)
},
onError: { [weak self] error, response in
self?.handleErrorAsync(error, response: response, isSimulated: simulated)
}
)
}
/**
Called asynchronously by image downloader when image is received.
- parameter image: Image received by the downloader.
- parameter isSimulated: True if the image was supplied by moa simulator rather than real network.
*/
private func handleSuccessAsync(_ image: MoaImage, isSimulated: Bool) {
var imageForView: MoaImage? = image
if let onSuccessAsync = onSuccessAsync {
imageForView = onSuccessAsync(image)
}
if isSimulated {
// Assign image in the same queue for simulated download to make unit testing simpler with synchronous code
handleSuccessMainQueue(imageForView)
} else {
DispatchQueue.main.async { [weak self] in
self?.handleSuccessMainQueue(imageForView)
}
}
}
/**
Called by image downloader in the main queue when image is received.
- parameter image: Image received by the downloader.
*/
private func handleSuccessMainQueue(_ image: MoaImage?) {
var imageForView: MoaImage? = image
if let onSuccess = onSuccess, image = image {
imageForView = onSuccess(image)
}
imageView?.image = imageForView
}
/**
Called asynchronously by image downloader if imaged download fails.
- parameter error: Error object.
- parameter response: HTTP response object, can be useful for getting HTTP status code.
- parameter isSimulated: True if the image was supplied by moa simulator rather than real network.
*/
private func handleErrorAsync(_ error: NSError?, response: HTTPURLResponse?, isSimulated: Bool) {
if let errorImage = globalOrInstanceErrorImage {
handleSuccessAsync(errorImage, isSimulated: isSimulated)
}
onErrorAsync?(error, response)
if let onError = onError {
DispatchQueue.main.async {
onError(error, response)
}
}
}
private var globalOrInstanceErrorImage: MoaImage? {
get {
return errorImage ?? Moa.errorImage
}
}
}
// ----------------------------
//
// MoaImageDownloader.swift
//
// ----------------------------
import Foundation
/// Downloads an image.
protocol MoaImageDownloader {
func startDownload(_ url: String, onSuccess: (MoaImage)->(),
onError: (NSError?, HTTPURLResponse?)->())
func cancel()
}
// ----------------------------
//
// MoaSettings.swift
//
// ----------------------------
/**
Settings for Moa image downloader.
*/
public struct MoaSettings {
/// Settings for caching of the images.
public var cache = MoaSettingsCache() {
didSet {
MoaHttpSession.cacheSettingsChanged(oldValue)
}
}
/// Timeout for image requests in seconds. This will cause a timeout if a resource is not able to be retrieved within a given timeout. Default timeout: 10 seconds.
public var requestTimeoutSeconds: Double = 10
/// Maximum number of simultaneous image downloads. Default: 4.
public var maximumSimultaneousDownloads: Int = 4
}
func ==(lhs: MoaSettings, rhs: MoaSettings) -> Bool {
return lhs.requestTimeoutSeconds == rhs.requestTimeoutSeconds
&& lhs.maximumSimultaneousDownloads == rhs.maximumSimultaneousDownloads
&& lhs.cache == rhs.cache
}
func !=(lhs: MoaSettings, rhs: MoaSettings) -> Bool {
return !(lhs == rhs)
}
// ----------------------------
//
// MoaSettingsCache.swift
//
// ----------------------------
import Foundation
/**
Specify settings for caching of downloaded images.
*/
public struct MoaSettingsCache {
/// The memory capacity of the cache, in bytes. Default value is 20 MB.
public var memoryCapacityBytes: Int = 20 * 1024 * 1024
/// The disk capacity of the cache, in bytes. Default value is 100 MB.
public var diskCapacityBytes: Int = 100 * 1024 * 1024
/**
The caching policy for the image downloads. The default value is .useProtocolCachePolicy.
* .useProtocolCachePolicy - Images are cached according to the the response HTTP headers, such as age and expiration date. This is the default cache policy.
* .reloadIgnoringLocalCacheData - Do not cache images locally. Always downloads the image from the source.
* .returnCacheDataElseLoad - Loads the image from local cache regardless of age and expiration date. If there is no existing image in the cache, the image is loaded from the source.
* .returnCacheDataDontLoad - Load the image from local cache only and do not attempt to load from the source.
*/
public var requestCachePolicy: NSURLRequest.CachePolicy = .useProtocolCachePolicy
/**
The name of a subdirectory of the application’s default cache directory
in which to store the on-disk cache.
*/
var diskPath = "moaImageDownloader"
}
func ==(lhs: MoaSettingsCache, rhs: MoaSettingsCache) -> Bool {
return lhs.memoryCapacityBytes == rhs.memoryCapacityBytes
&& lhs.diskCapacityBytes == rhs.diskCapacityBytes
&& lhs.requestCachePolicy == rhs.requestCachePolicy
&& lhs.diskPath == rhs.diskPath
}
func !=(lhs: MoaSettingsCache, rhs: MoaSettingsCache) -> Bool {
return !(lhs == rhs)
}
// ----------------------------
//
// MoaSimulatedImageDownloader.swift
//
// ----------------------------
import Foundation
/**
Simulates download of images in unit test. This downloader is used instead of the HTTP downloaded when the moa simulator is started: MoaSimulator.start().
*/
public final class MoaSimulatedImageDownloader: MoaImageDownloader {
/// Url of the downloader.
public let url: String
/// Indicates if the request was cancelled.
public var cancelled = false
var autorespondWithImage: MoaImage?
var autorespondWithError: (error: NSError?, response: HTTPURLResponse?)?
var onSuccess: ((MoaImage)->())?
var onError: ((NSError, HTTPURLResponse?)->())?
init(url: String) {
self.url = url
}
func startDownload(_ url: String, onSuccess: (MoaImage)->(),
onError: (NSError?, HTTPURLResponse?)->()) {
self.onSuccess = onSuccess
self.onError = onError
if let autorespondWithImage = autorespondWithImage {
respondWithImage(autorespondWithImage)
}
if let autorespondWithError = autorespondWithError {
respondWithError(autorespondWithError.error, response: autorespondWithError.response)
}
}
func cancel() {
cancelled = true
}
/**
Simulate a successful server response with the supplied image.
- parameter image: Image that is be passed to success handler of all ongoing requests.
*/
public func respondWithImage(_ image: MoaImage) {
onSuccess?(image)
}
/**
Simulate an error response from server.
- parameter error: Optional error that is passed to the error handler ongoing request.
- parameter response: Optional response that is passed to the error handler ongoing request.
*/
public func respondWithError(_ error: NSError? = nil, response: HTTPURLResponse? = nil) {
onError?(error ?? MoaError.simulatedError.nsError, response)
}
}
// ----------------------------
//
// MoaSimulator.swift
//
// ----------------------------
import Foundation
/**
Simulates image download in unit tests instead of sending real network requests.