-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathPINRemoteImageManager.m
1652 lines (1441 loc) · 71.5 KB
/
PINRemoteImageManager.m
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
//
// PINRemoteImageManager.m
// Pods
//
// Created by Garrett Moon on 8/17/14.
//
//
#import "PINRemoteImageManager.h"
#import <CommonCrypto/CommonDigest.h>
#import <PINOperation/PINOperation.h>
#import <objc/runtime.h>
#import "PINAlternateRepresentationProvider.h"
#import "PINRemoteImage.h"
#import "PINRemoteImageManagerConfiguration.h"
#import "PINRemoteLock.h"
#import "PINProgressiveImage.h"
#import "PINRemoteImageCallbacks.h"
#import "PINRemoteImageTask.h"
#import "PINRemoteImageProcessorTask.h"
#import "PINRemoteImageDownloadTask.h"
#import "PINResume.h"
#import "PINRemoteImageMemoryContainer.h"
#import "PINRemoteImageCaching.h"
#import "PINRequestRetryStrategy.h"
#import "PINRemoteImageDownloadQueue.h"
#import "PINRequestRetryStrategy.h"
#import "PINSpeedRecorder.h"
#import "PINURLSessionManager.h"
#import "NSData+ImageDetectors.h"
#import "PINImage+DecodedImage.h"
#import "PINImage+ScaledImage.h"
#import "PINRemoteImageManager+Private.h"
#import "NSHTTPURLResponse+MaxAge.h"
#if USE_PINCACHE
#import "PINCache+PINRemoteImageCaching.h"
#else
#import "PINRemoteImageBasicCache.h"
#endif
#define PINRemoteImageManagerDefaultTimeout 30.0
//A limit of 200 characters is chosen because PINDiskCache
//may expand the length by encoding certain characters
#define PINRemoteImageManagerCacheKeyMaxLength 200
PINOperationQueuePriority operationPriorityWithImageManagerPriority(PINRemoteImageManagerPriority priority);
PINOperationQueuePriority operationPriorityWithImageManagerPriority(PINRemoteImageManagerPriority priority) {
switch (priority) {
case PINRemoteImageManagerPriorityLow:
return PINOperationQueuePriorityLow;
break;
case PINRemoteImageManagerPriorityDefault:
return PINOperationQueuePriorityDefault;
break;
case PINRemoteImageManagerPriorityHigh:
return PINOperationQueuePriorityHigh;
break;
}
}
float dataTaskPriorityWithImageManagerPriority(PINRemoteImageManagerPriority priority) {
switch (priority) {
case PINRemoteImageManagerPriorityLow:
return 0.0;
break;
case PINRemoteImageManagerPriorityDefault:
return 0.5;
break;
case PINRemoteImageManagerPriorityHigh:
return 1.0;
break;
}
}
// Reference: https://github.com/TextureGroup/Texture/blob/5dd5611/Source/Private/ASInternalHelpers.m#L60
BOOL PINRemoteImageManagerSubclassOverridesSelector(Class subclass, SEL selector)
{
Class superclass = [PINRemoteImageManager class];
if (superclass == subclass) return NO; // Even if the class implements the selector, it doesn't override itself.
Method superclassMethod = class_getInstanceMethod(superclass, selector);
Method subclassMethod = class_getInstanceMethod(subclass, selector);
return (superclassMethod != subclassMethod);
}
NSErrorDomain const PINRemoteImageManagerErrorDomain = @"PINRemoteImageManagerErrorDomain";
NSString * const PINRemoteImageCacheKey = @"cacheKey";
NSString * const PINRemoteImageCacheKeyResumePrefix = @"R-";
typedef void (^PINRemoteImageManagerDataCompletion)(NSData *data, NSURLResponse *response, NSError *error);
@interface PINRemoteImageManager () <PINURLSessionManagerDelegate>
{
dispatch_queue_t _callbackQueue;
PINRemoteLock *_lock;
PINOperationQueue *_concurrentOperationQueue;
PINRemoteImageDownloadQueue *_urlSessionTaskQueue;
// Necesarry to have a strong reference to _defaultAlternateRepresentationProvider because _alternateRepProvider is __weak
PINAlternateRepresentationProvider *_defaultAlternateRepresentationProvider;
__weak PINAlternateRepresentationProvider *_alternateRepProvider;
NSURLSessionConfiguration *_sessionConfiguration;
}
@property (nonatomic, strong) id<PINRemoteImageCaching> cache;
@property (nonatomic, strong) PINURLSessionManager *sessionManager;
@property (nonatomic, strong) NSMutableDictionary <NSString *, __kindof PINRemoteImageTask *> *tasks;
@property (nonatomic, strong) NSHashTable <NSUUID *> *canceledTasks;
@property (nonatomic, strong) NSHashTable <NSUUID *> *UUIDs;
@property (nonatomic, strong) NSArray <NSNumber *> *progressThresholds;
@property (nonatomic, assign) BOOL shouldBlurProgressive;
@property (nonatomic, assign) CGSize maxProgressiveRenderSize;
@property (nonatomic, assign) NSTimeInterval estimatedRemainingTimeThreshold;
@property (nonatomic, strong) dispatch_queue_t callbackQueue;
@property (nonatomic, strong) PINOperationQueue *concurrentOperationQueue;
@property (nonatomic, strong) PINRemoteImageDownloadQueue *urlSessionTaskQueue;
@property (nonatomic, assign) float highQualityBPSThreshold;
@property (nonatomic, assign) float lowQualityBPSThreshold;
@property (nonatomic, assign) BOOL shouldUpgradeLowQualityImages;
@property (nonatomic, strong) PINRemoteImageManagerMetrics metricsCallback API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
@property (nonatomic, copy) PINRemoteImageManagerAuthenticationChallenge authenticationChallengeHandler;
@property (nonatomic, copy) id<PINRequestRetryStrategy> (^retryStrategyCreationBlock)(void);
@property (nonatomic, copy) PINRemoteImageManagerRequestConfigurationHandler requestConfigurationHandler;
@property (nonatomic, strong) NSMutableDictionary <NSString *, NSString *> *httpHeaderFields;
@property (nonatomic, readonly) BOOL diskCacheTTLIsEnabled;
@property (nonatomic, readonly) BOOL memoryCacheTTLIsEnabled;
#if DEBUG
@property (nonatomic, assign) NSUInteger totalDownloads;
#endif
@end
#pragma mark PINRemoteImageManager
@implementation PINRemoteImageManager
static PINRemoteImageManager *sharedImageManager = nil;
static dispatch_once_t sharedDispatchToken;
+ (instancetype)sharedImageManager
{
dispatch_once(&sharedDispatchToken, ^{
sharedImageManager = [[[self class] alloc] init];
});
return sharedImageManager;
}
+ (void)setSharedImageManagerWithConfiguration:(NSURLSessionConfiguration *)configuration
{
NSAssert(sharedImageManager == nil, @"sharedImageManager singleton is already configured");
dispatch_once(&sharedDispatchToken, ^{
sharedImageManager = [[[self class] alloc] initWithSessionConfiguration:configuration];
});
}
- (instancetype)init
{
return [self initWithSessionConfiguration:nil];
}
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration
{
return [self initWithSessionConfiguration:sessionConfiguration alternativeRepresentationProvider:nil];
}
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration alternativeRepresentationProvider:(id <PINRemoteImageManagerAlternateRepresentationProvider>)alternateRepProvider
{
return [self initWithSessionConfiguration:sessionConfiguration alternativeRepresentationProvider:alternateRepProvider imageCache:nil managerConfiguration:nil];
}
- (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration
alternativeRepresentationProvider:(nullable id <PINRemoteImageManagerAlternateRepresentationProvider>)alternateRepDelegate
imageCache:(nullable id<PINRemoteImageCaching>)imageCache {
return [self initWithSessionConfiguration:sessionConfiguration alternativeRepresentationProvider:alternateRepDelegate imageCache:imageCache managerConfiguration:nil];
}
-(nonnull instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)sessionConfiguration
alternativeRepresentationProvider:(id<PINRemoteImageManagerAlternateRepresentationProvider>)alternateRepProvider
imageCache:(id<PINRemoteImageCaching>)imageCache
managerConfiguration:(nullable PINRemoteImageManagerConfiguration *)managerConfiguration
{
if (self = [super init]) {
PINRemoteImageManagerConfiguration *configuration = managerConfiguration;
if (!configuration) {
configuration = [[PINRemoteImageManagerConfiguration alloc] init];
}
if (imageCache) {
self.cache = imageCache;
} else if (PINRemoteImageManagerSubclassOverridesSelector([self class], @selector(defaultImageCache))) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
self.cache = [self defaultImageCache];
#pragma clang diagnostic pop
} else {
self.cache = [[self class] defaultImageCache];
}
if ([self.cache respondsToSelector:@selector(setObjectOnDisk:forKey:withAgeLimit:)] &&
[self.cache respondsToSelector:@selector(setObjectInMemory:forKey:withCost:withAgeLimit:)] &&
[self.cache respondsToSelector:@selector(diskCacheIsTTLCache)] &&
[self.cache respondsToSelector:@selector(memoryCacheIsTTLCache)]) {
_diskCacheTTLIsEnabled = [self.cache diskCacheIsTTLCache];
_memoryCacheTTLIsEnabled = [self.cache memoryCacheIsTTLCache];
}
_sessionConfiguration = [sessionConfiguration copy];
if (!_sessionConfiguration) {
_sessionConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
_sessionConfiguration.timeoutIntervalForRequest = PINRemoteImageManagerDefaultTimeout;
_sessionConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
_sessionConfiguration.URLCache = nil;
}
_sessionConfiguration.HTTPMaximumConnectionsPerHost = PINRemoteImageHTTPMaximumConnectionsPerHost;
_callbackQueue = dispatch_queue_create("PINRemoteImageManagerCallbackQueue", DISPATCH_QUEUE_CONCURRENT);
_lock = [[PINRemoteLock alloc] initWithName:@"PINRemoteImageManager"];
_concurrentOperationQueue = [[PINOperationQueue alloc] initWithMaxConcurrentOperations: configuration.maxConcurrentOperations];
_urlSessionTaskQueue = [PINRemoteImageDownloadQueue queueWithMaxConcurrentDownloads:configuration.maxConcurrentDownloads];
self.sessionManager = [[PINURLSessionManager alloc] initWithSessionConfiguration:_sessionConfiguration];
self.sessionManager.delegate = self;
self.estimatedRemainingTimeThreshold = configuration.estimatedRemainingTimeThreshold;
_highQualityBPSThreshold = configuration.highQualityBPSThreshold;
_lowQualityBPSThreshold = configuration.lowQualityBPSThreshold;
_shouldUpgradeLowQualityImages = configuration.shouldUpgradeLowQualityImages;
_shouldBlurProgressive = configuration.shouldBlurProgressive;
_maxProgressiveRenderSize = configuration.maxProgressiveRenderSize;
self.tasks = [[NSMutableDictionary alloc] init];
self.canceledTasks = [[NSHashTable alloc] initWithOptions:NSHashTableWeakMemory capacity:5];
self.UUIDs = [NSHashTable weakObjectsHashTable];
if (alternateRepProvider == nil) {
_defaultAlternateRepresentationProvider = [[PINAlternateRepresentationProvider alloc] init];
alternateRepProvider = _defaultAlternateRepresentationProvider;
}
_alternateRepProvider = alternateRepProvider;
__weak typeof(self) weakSelf = self;
_retryStrategyCreationBlock = ^id<PINRequestRetryStrategy>{
return [weakSelf defaultRetryStrategy];
};
_httpHeaderFields = [[NSMutableDictionary alloc] init];
}
return self;
}
- (id<PINRequestRetryStrategy>)defaultRetryStrategy {
return [[PINRequestExponentialRetryStrategy alloc] initWithRetryMaxCount:3 delayBase:4];
}
- (void)dealloc
{
[self.sessionManager invalidateSessionAndCancelTasks];
}
- (id<PINRemoteImageCaching>)defaultImageCache {
return [PINRemoteImageManager defaultImageCache];
}
+ (id<PINRemoteImageCaching>)defaultImageCache {
return [PINRemoteImageManager defaultImageCacheEnablingTtl:NO];
}
+ (id<PINRemoteImageCaching>)defaultImageTtlCache {
return [PINRemoteImageManager defaultImageCacheEnablingTtl:YES];
}
+ (id<PINRemoteImageCaching>)defaultImageCacheEnablingTtl:(BOOL)enableTtl
{
#if USE_PINCACHE
NSString * const kPINRemoteImageDiskCacheName = @"PINRemoteImageManagerCache";
NSString * const kPINRemoteImageDiskCacheVersionKey = @"kPINRemoteImageDiskCacheVersionKey";
const NSInteger kPINRemoteImageDiskCacheVersion = 1;
NSUserDefaults *pinDefaults = [[NSUserDefaults alloc] init];
NSString *cacheURLRoot = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if ([pinDefaults integerForKey:kPINRemoteImageDiskCacheVersionKey] != kPINRemoteImageDiskCacheVersion) {
//remove the old version of the disk cache
NSURL *diskCacheURL = [PINDiskCache cacheURLWithRootPath:cacheURLRoot prefix:PINDiskCachePrefix name:kPINRemoteImageDiskCacheName];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *dstURL = [[[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:kPINRemoteImageDiskCacheName];
[fileManager moveItemAtURL:diskCacheURL toURL:dstURL error:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[fileManager removeItemAtURL:dstURL error:nil];
});
[pinDefaults setInteger:kPINRemoteImageDiskCacheVersion forKey:kPINRemoteImageDiskCacheVersionKey];
}
PINCache *pinCache = [[PINCache alloc] initWithName:kPINRemoteImageDiskCacheName rootPath:cacheURLRoot serializer:^NSData * _Nonnull(id<NSCoding> _Nonnull object, NSString * _Nonnull key) {
id <NSCoding, NSObject> obj = (id <NSCoding, NSObject>)object;
if ([key hasPrefix:PINRemoteImageCacheKeyResumePrefix]) {
return [NSKeyedArchiver archivedDataWithRootObject:obj];
}
return (NSData *)object;
} deserializer:^id<NSCoding> _Nonnull(NSData * _Nonnull data, NSString * _Nonnull key) {
if ([key hasPrefix:PINRemoteImageCacheKeyResumePrefix]) {
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
return data;
} keyEncoder:nil keyDecoder:nil ttlCache:enableTtl];
return pinCache;
#else
return [[PINRemoteImageBasicCache alloc] init];
#endif
}
- (void)lockOnMainThread
{
#if !DEBUG
NSAssert(NO, @"lockOnMainThread should only be called for testing on debug builds!");
#endif
[_lock lock];
}
- (void)lock
{
NSAssert([NSThread isMainThread] == NO, @"lock should not be called from the main thread!");
[_lock lock];
}
- (void)unlock
{
[_lock unlock];
}
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)header {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.httpHeaderFields[[header copy]] = [value copy];
[strongSelf unlock];
});
}
- (void)setRequestConfiguration:(PINRemoteImageManagerRequestConfigurationHandler)configurationBlock {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.requestConfigurationHandler = configurationBlock;
[strongSelf unlock];
});
}
- (void)setAuthenticationChallenge:(PINRemoteImageManagerAuthenticationChallenge)challengeBlock {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.authenticationChallengeHandler = challengeBlock;
[strongSelf unlock];
});
}
- (void)setMaxNumberOfConcurrentOperations:(NSInteger)maxNumberOfConcurrentOperations completion:(dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.concurrentOperationQueue.maxConcurrentOperations = maxNumberOfConcurrentOperations;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setMaxNumberOfConcurrentDownloads:(NSInteger)maxNumberOfConcurrentDownloads completion:(dispatch_block_t)completion
{
NSAssert(maxNumberOfConcurrentDownloads <= PINRemoteImageHTTPMaximumConnectionsPerHost, @"maxNumberOfConcurrentDownloads must be less than or equal to %d", PINRemoteImageHTTPMaximumConnectionsPerHost);
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.urlSessionTaskQueue.maxNumberOfConcurrentDownloads = maxNumberOfConcurrentDownloads;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setEstimatedRemainingTimeThresholdForProgressiveDownloads:(NSTimeInterval)estimatedRemainingTimeThreshold completion:(dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.estimatedRemainingTimeThreshold = estimatedRemainingTimeThreshold;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setProgressThresholds:(NSArray *)progressThresholds completion:(dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.progressThresholds = progressThresholds;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setProgressiveRendersShouldBlur:(BOOL)shouldBlur completion:(nullable dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.shouldBlurProgressive = shouldBlur;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setProgressiveRendersMaxProgressiveRenderSize:(CGSize)maxProgressiveRenderSize completion:(nullable dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.maxProgressiveRenderSize = maxProgressiveRenderSize;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setHighQualityBPSThreshold:(float)highQualityBPSThreshold completion:(dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.highQualityBPSThreshold = highQualityBPSThreshold;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setLowQualityBPSThreshold:(float)lowQualityBPSThreshold completion:(dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.lowQualityBPSThreshold = lowQualityBPSThreshold;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setShouldUpgradeLowQualityImages:(BOOL)shouldUpgradeLowQualityImages completion:(dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.shouldUpgradeLowQualityImages = shouldUpgradeLowQualityImages;
[strongSelf unlock];
if (completion) {
completion();
}
});
}
- (void)setMetricsCallback:(nullable PINRemoteImageManagerMetrics)metricsCallback completion:(nullable dispatch_block_t)completion
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[self lock];
strongSelf.metricsCallback = metricsCallback;
[self unlock];
if (completion) {
completion();
}
});
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:PINRemoteImageManagerDownloadOptionsNone
completion:completion];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:options
progressImage:nil
completion:completion];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
progressImage:(PINRemoteImageManagerImageCompletion)progressImage
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:options
progressImage:progressImage
progressDownload:nil
completion:completion];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:options
progressImage:nil
progressDownload:progressDownload
completion:completion];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
progressImage:(PINRemoteImageManagerImageCompletion)progressImage
progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:options
priority:PINRemoteImageManagerPriorityDefault
progressImage:progressImage
progressDownload:progressDownload
completion:completion];
}
- (nullable NSUUID *)downloadImageWithURL:(nonnull NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
priority:(PINRemoteImageManagerPriority)priority
progressImage:(PINRemoteImageManagerImageCompletion)progressImage
progressDownload:(nullable PINRemoteImageManagerProgressDownload)progressDownload
completion:(nullable PINRemoteImageManagerImageCompletion)completion;
{
return [self downloadImageWithURL:url
options:options
priority:priority
processorKey:nil
processor:nil
progressImage:progressImage
progressDownload:progressDownload
completion:completion
inputUUID:nil];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
processorKey:(NSString *)processorKey
processor:(PINRemoteImageManagerImageProcessor)processor
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:options
priority:PINRemoteImageManagerPriorityDefault
processorKey:processorKey
processor:processor
progressImage:nil
progressDownload:nil
completion:completion
inputUUID:nil];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
processorKey:(NSString *)processorKey
processor:(PINRemoteImageManagerImageProcessor)processor
progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
completion:(PINRemoteImageManagerImageCompletion)completion
{
return [self downloadImageWithURL:url
options:options
priority:PINRemoteImageManagerPriorityDefault
processorKey:processorKey
processor:processor
progressImage:nil
progressDownload:progressDownload
completion:completion
inputUUID:nil];
}
- (NSUUID *)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
priority:(PINRemoteImageManagerPriority)priority
processorKey:(NSString *)processorKey
processor:(PINRemoteImageManagerImageProcessor)processor
progressImage:(PINRemoteImageManagerImageCompletion)progressImage
progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
completion:(PINRemoteImageManagerImageCompletion)completion
inputUUID:(NSUUID *)UUID
{
NSAssert((processor != nil && processorKey.length > 0) || (processor == nil && processorKey == nil), @"processor must not be nil and processorKey length must be greater than zero OR processor must be nil and processorKey must be nil");
Class taskClass;
if (processor && processorKey.length > 0) {
taskClass = [PINRemoteImageProcessorTask class];
} else {
taskClass = [PINRemoteImageDownloadTask class];
}
NSString *key = [self cacheKeyForURL:url processorKey:processorKey];
if (url == nil) {
[self earlyReturnWithOptions:options url:nil key:key object:nil completion:completion];
return nil;
}
NSAssert([url isKindOfClass:[NSURL class]], @"url must be of type NSURL, if it's an NSString, we'll try to correct");
if ([url isKindOfClass:[NSString class]]) {
url = [NSURL URLWithString:(NSString *)url];
}
if (UUID == nil) {
UUID = [NSUUID UUID];
}
if ((options & PINRemoteImageManagerDownloadOptionsIgnoreCache) == 0) {
//Check to see if the image is in memory cache and we're on the main thread.
//If so, special case this to avoid flashing the UI
id object = [self.cache objectFromMemoryForKey:key];
if (object) {
if ([self earlyReturnWithOptions:options url:url key:key object:object completion:completion]) {
return nil;
}
}
}
if ([url.scheme isEqualToString:@"data"]) {
NSData *data = [NSData dataWithContentsOfURL:url];
if (data) {
if ([self earlyReturnWithOptions:options url:url key:key object:data completion:completion]) {
return nil;
}
}
}
[_concurrentOperationQueue scheduleOperation:^
{
[self lock];
//check canceled tasks first
if ([self.canceledTasks containsObject:UUID]) {
PINLog(@"skipping starting %@ because it was canceled.", UUID);
[self unlock];
return;
}
PINRemoteImageTask *task = [self.tasks objectForKey:key];
BOOL taskExisted = NO;
if (task == nil) {
task = [[taskClass alloc] initWithManager:self];
PINLog(@"Task does not exist creating with key: %@, URL: %@, UUID: %@, task: %p", key, url, UUID, task);
#if PINRemoteImageLogging
task.key = key;
#endif
} else {
taskExisted = YES;
PINLog(@"Task exists, attaching with key: %@, URL: %@, UUID: %@, task: %@", key, url, UUID, task);
}
[task addCallbacksWithCompletionBlock:completion progressImageBlock:progressImage progressDownloadBlock:progressDownload withUUID:UUID];
[self.tasks setObject:task forKey:key];
// Relax :), task retain the UUID for us, it's ok to have a weak reference to UUID here.
[self.UUIDs addObject:UUID];
NSAssert(taskClass == [task class], @"Task class should be the same!");
[self unlock];
if (taskExisted == NO) {
[self.concurrentOperationQueue scheduleOperation:^
{
[self objectForKey:key options:options completion:^(BOOL found, BOOL valid, PINImage *image, id alternativeRepresentation) {
if (found) {
if (valid) {
[self callCompletionsWithKey:key image:image alternativeRepresentation:alternativeRepresentation cached:YES response:nil error:nil finalized:YES];
} else {
//Remove completion and try again
[self lock];
PINRemoteImageTask *task = [self.tasks objectForKey:key];
[task removeCallbackWithUUID:UUID];
if (task.callbackBlocks.count == 0) {
[self.tasks removeObjectForKey:key];
}
[self unlock];
//Skip early check
[self downloadImageWithURL:url
options:options | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck
priority:priority
processorKey:processorKey
processor:processor
progressImage:(PINRemoteImageManagerImageCompletion)progressImage
progressDownload:nil
completion:completion
inputUUID:UUID];
}
} else {
if ([taskClass isSubclassOfClass:[PINRemoteImageProcessorTask class]]) {
//continue processing
[self downloadImageWithURL:url
options:options
priority:priority
key:key
processor:processor
UUID:UUID];
} else if ([taskClass isSubclassOfClass:[PINRemoteImageDownloadTask class]]) {
//continue downloading
[self downloadImageWithURL:url
options:options
priority:priority
key:key
progressImage:progressImage
UUID:UUID];
}
}
}];
} withPriority:operationPriorityWithImageManagerPriority(priority)];
}
} withPriority:operationPriorityWithImageManagerPriority(priority)];
return UUID;
}
- (void)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
priority:(PINRemoteImageManagerPriority)priority
key:(NSString *)key
processor:(PINRemoteImageManagerImageProcessor)processor
UUID:(NSUUID *)UUID
{
PINRemoteImageProcessorTask *task = nil;
[self lock];
task = [self.tasks objectForKey:key];
//check processing task still exists and download hasn't been started for another task
if (task == nil || task.downloadTaskUUID != nil) {
[self unlock];
return;
}
__weak typeof(self) weakSelf = self;
NSUUID *downloadTaskUUID = [self downloadImageWithURL:url
options:options | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck | PINRemoteImageManagerDisallowAlternateRepresentations
completion:^(PINRemoteImageManagerResult *result)
{
typeof(self) strongSelf = weakSelf;
NSUInteger processCost = 0;
NSError *error = result.error;
PINRemoteImageProcessorTask *task = nil;
[strongSelf lock];
task = [strongSelf.tasks objectForKey:key];
[strongSelf unlock];
//check processing task still exists
if (task == nil) {
return;
}
if (result.image && error == nil) {
//If completionBlocks.count == 0, we've canceled before we were even able to start.
PINImage *image = processor(result, &processCost);
if (image == nil) {
error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
code:PINRemoteImageManagerErrorFailedToProcessImage
userInfo:nil];
}
[strongSelf callCompletionsWithKey:key image:image alternativeRepresentation:nil cached:NO response:result.response error:error finalized:NO];
if (error == nil && image != nil) {
BOOL saveAsJPEG = (options & PINRemoteImageManagerSaveProcessedImageAsJPEG) != 0;
NSData *diskData = nil;
if (saveAsJPEG) {
diskData = PINImageJPEGRepresentation(image, 1.0);
} else {
diskData = PINImagePNGRepresentation(image);
}
[strongSelf materializeAndCacheObject:image cacheInDisk:diskData additionalCost:processCost url:url key:key options:options outImage:nil outAltRep:nil];
}
[strongSelf callCompletionsWithKey:key image:image alternativeRepresentation:nil cached:NO response:result.response error:error finalized:YES];
} else {
if (error == nil) {
error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
code:PINRemoteImageManagerErrorFailedToFetchImageForProcessing
userInfo:nil];
}
[strongSelf callCompletionsWithKey:key image:nil alternativeRepresentation:nil cached:NO response:result.response error:error finalized:YES];
}
}];
task.downloadTaskUUID = downloadTaskUUID;
[self unlock];
}
- (void)downloadImageWithURL:(NSURL *)url
options:(PINRemoteImageManagerDownloadOptions)options
priority:(PINRemoteImageManagerPriority)priority
key:(NSString *)key
progressImage:(PINRemoteImageManagerImageCompletion)progressImage
UUID:(NSUUID *)UUID
{
PINResume *resume = nil;
if ((options & PINRemoteImageManagerDownloadOptionsIgnoreCache) == NO) {
NSString *resumeKey = [self resumeCacheKeyForURL:url];
resume = [self.cache objectFromDiskForKey:resumeKey];
[self.cache removeObjectForKey:resumeKey completion:nil];
}
[self lock];
PINRemoteImageDownloadTask *task = [self.tasks objectForKey:key];
[self unlock];
[task scheduleDownloadWithRequest:[self requestWithURL:url key:key]
resume:resume
skipRetry:(options & PINRemoteImageManagerDownloadOptionsSkipRetry)
priority:priority
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
[self->_concurrentOperationQueue scheduleOperation:^
{
NSError *remoteImageError = error;
PINImage *image = nil;
id alternativeRepresentation = nil;
NSNumber *maxAge = nil;
if (remoteImageError == nil) {
BOOL ignoreHeaders = (options & PINRemoteImageManagerDownloadOptionsIgnoreCacheControlHeaders) != 0;
if ((self.diskCacheTTLIsEnabled || self.memoryCacheTTLIsEnabled) && !ignoreHeaders) {
// examine Cache-Control headers (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
maxAge = [httpResponse findMaxAge];
}
}
// Stores the object in the cache.
[self materializeAndCacheObject:data cacheInDisk:data additionalCost:0 maxAge:maxAge url:url key:key options:options outImage:&image outAltRep:&alternativeRepresentation];
}
if (error == nil && image == nil && alternativeRepresentation == nil) {
remoteImageError = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
code:PINRemoteImageManagerErrorFailedToDecodeImage
userInfo:nil];
}
[self callCompletionsWithKey:key image:image alternativeRepresentation:alternativeRepresentation cached:NO response:response error:remoteImageError finalized:YES];
} withPriority:operationPriorityWithImageManagerPriority(priority)];
}];
}
-(BOOL)insertImageDataIntoCache:(nonnull NSData*)data
withURL:(nonnull NSURL *)url
processorKey:(nullable NSString *)processorKey
additionalCost:(NSUInteger)additionalCost
{
if (url != nil) {
NSString *key = [self cacheKeyForURL:url processorKey:processorKey];
PINRemoteImageManagerDownloadOptions options = PINRemoteImageManagerDownloadOptionsSkipDecode | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck;
PINRemoteImageMemoryContainer *container = [[PINRemoteImageMemoryContainer alloc] init];
container.data = data;
return [self materializeAndCacheObject:container cacheInDisk:data additionalCost:additionalCost url:url key:key options:options outImage: nil outAltRep: nil];
}
return NO;
}
- (BOOL)earlyReturnWithOptions:(PINRemoteImageManagerDownloadOptions)options url:(NSURL *)url key:(NSString *)key object:(id)object completion:(PINRemoteImageManagerImageCompletion)completion
{
PINImage *image = nil;
id alternativeRepresentation = nil;
PINRemoteImageResultType resultType = PINRemoteImageResultTypeNone;
BOOL allowEarlyReturn = !(PINRemoteImageManagerDownloadOptionsSkipEarlyCheck & options);
if (url != nil && object != nil) {
resultType = PINRemoteImageResultTypeMemoryCache;
[self materializeAndCacheObject:object url:url key:key options:options outImage:&image outAltRep:&alternativeRepresentation];
}
if (completion && ((image || alternativeRepresentation) || (url == nil))) {
//If we're on the main thread, special case to call completion immediately
NSError *error = nil;
if (!url) {
error = [NSError errorWithDomain:NSURLErrorDomain
code:NSURLErrorUnsupportedURL
userInfo:@{ NSLocalizedDescriptionKey : @"unsupported URL" }];
}
PINRemoteImageManagerResult *result = [PINRemoteImageManagerResult imageResultWithImage:image
alternativeRepresentation:alternativeRepresentation
requestLength:0
resultType:resultType
UUID:nil
response:nil
error:error];
if (allowEarlyReturn && [NSThread isMainThread]) {
completion(result);
} else {
dispatch_async(self.callbackQueue, ^{
completion(result);
});
}
return YES;
}
return NO;
}
- (NSURLRequest *)requestWithURL:(NSURL *)url key:(NSString *)key
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *headers = [self.httpHeaderFields mutableCopy];
if (headers.count > 0) {
request.allHTTPHeaderFields = headers;
}
if (_requestConfigurationHandler) {
request = [_requestConfigurationHandler(request) mutableCopy];
}
[NSURLProtocol setProperty:key forKey:PINRemoteImageCacheKey inRequest:request];
return request;
}
- (void)callCompletionsWithKey:(NSString *)key
image:(PINImage *)image
alternativeRepresentation:(id)alternativeRepresentation
cached:(BOOL)cached
response:(NSURLResponse *)response
error:(NSError *)error
finalized:(BOOL)finalized
{
[self lock];
PINRemoteImageDownloadTask *task = [self.tasks objectForKey:key];
[task callCompletionsWithImage:image alternativeRepresentation:alternativeRepresentation cached:cached response:response error:error remove:!finalized];
if (finalized) {
[self.tasks removeObjectForKey:key];
}
[self unlock];
}
#pragma mark - Prefetching
- (NSArray<NSUUID *> *)prefetchImagesWithURLs:(NSArray <NSURL *> *)urls
{
return [self prefetchImagesWithURLs:urls options:PINRemoteImageManagerDownloadOptionsNone | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck];
}
- (NSArray<NSUUID *> *)prefetchImagesWithURLs:(NSArray <NSURL *> *)urls options:(PINRemoteImageManagerDownloadOptions)options
{
return [self prefetchImagesWithURLs:urls options:options priority:PINRemoteImageManagerPriorityLow];
}
- (NSArray<NSUUID *> *)prefetchImagesWithURLs:(NSArray <NSURL *> *)urls options:(PINRemoteImageManagerDownloadOptions)options priority:(PINRemoteImageManagerPriority)priority
{
NSMutableArray *tasks = [NSMutableArray arrayWithCapacity:urls.count];
for (NSURL *url in urls) {
NSUUID *task = [self prefetchImageWithURL:url options:options priority:priority];
if (task != nil) {
[tasks addObject:task];
}
}