PINRemoteImageManager.m 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  1. //
  2. // PINRemoteImageManager.m
  3. // Pods
  4. //
  5. // Created by Garrett Moon on 8/17/14.
  6. //
  7. //
  8. #import "PINRemoteImageManager.h"
  9. #import <CommonCrypto/CommonDigest.h>
  10. #import "PINAlternateRepresentationProvider.h"
  11. #import "PINRemoteImage.h"
  12. #import "PINRemoteLock.h"
  13. #import "PINProgressiveImage.h"
  14. #import "PINRemoteImageCallbacks.h"
  15. #import "PINRemoteImageTask.h"
  16. #import "PINRemoteImageProcessorTask.h"
  17. #import "PINRemoteImageDownloadTask.h"
  18. #import "PINDataTaskOperation.h"
  19. #import "PINURLSessionManager.h"
  20. #import "PINRemoteImageMemoryContainer.h"
  21. #import "PINRemoteImageCaching.h"
  22. #import "NSData+ImageDetectors.h"
  23. #import "PINImage+DecodedImage.h"
  24. #if USE_PINCACHE
  25. #import "PINCache+PINRemoteImageCaching.h"
  26. #else
  27. #import "PINRemoteImageBasicCache.h"
  28. #endif
  29. #define PINRemoteImageManagerDefaultTimeout 30.0
  30. #define PINRemoteImageMaxRetries 3
  31. #define PINRemoteImageRetryDelayBase 4
  32. //A limit of 200 characters is chosen because PINDiskCache
  33. //may expand the length by encoding certain characters
  34. #define PINRemoteImageManagerCacheKeyMaxLength 200
  35. NSOperationQueuePriority operationPriorityWithImageManagerPriority(PINRemoteImageManagerPriority priority) {
  36. switch (priority) {
  37. case PINRemoteImageManagerPriorityVeryLow:
  38. return NSOperationQueuePriorityVeryLow;
  39. break;
  40. case PINRemoteImageManagerPriorityLow:
  41. return NSOperationQueuePriorityLow;
  42. break;
  43. case PINRemoteImageManagerPriorityMedium:
  44. return NSOperationQueuePriorityNormal;
  45. break;
  46. case PINRemoteImageManagerPriorityHigh:
  47. return NSOperationQueuePriorityHigh;
  48. break;
  49. case PINRemoteImageManagerPriorityVeryHigh:
  50. return NSOperationQueuePriorityVeryHigh;
  51. break;
  52. }
  53. }
  54. float dataTaskPriorityWithImageManagerPriority(PINRemoteImageManagerPriority priority) {
  55. switch (priority) {
  56. case PINRemoteImageManagerPriorityVeryLow:
  57. return 0.0;
  58. break;
  59. case PINRemoteImageManagerPriorityLow:
  60. return 0.25;
  61. break;
  62. case PINRemoteImageManagerPriorityMedium:
  63. return 0.5;
  64. break;
  65. case PINRemoteImageManagerPriorityHigh:
  66. return 0.75;
  67. break;
  68. case PINRemoteImageManagerPriorityVeryHigh:
  69. return 1.0;
  70. break;
  71. }
  72. }
  73. NSString * const PINRemoteImageManagerErrorDomain = @"PINRemoteImageManagerErrorDomain";
  74. NSString * const PINRemoteImageCacheKey = @"cacheKey";
  75. typedef void (^PINRemoteImageManagerDataCompletion)(NSData *data, NSError *error);
  76. @interface NSOperationQueue (PINRemoteImageManager)
  77. - (void)pin_addOperationWithQueuePriority:(PINRemoteImageManagerPriority)priority block:(void (^)(void))block;
  78. @end
  79. @interface PINTaskQOS : NSObject
  80. - (instancetype)initWithBPS:(float)bytesPerSecond endDate:(NSDate *)endDate;
  81. @property (nonatomic, strong) NSDate *endDate;
  82. @property (nonatomic, assign) float bytesPerSecond;
  83. @end
  84. @interface PINRemoteImageManager () <PINURLSessionManagerDelegate>
  85. {
  86. dispatch_queue_t _callbackQueue;
  87. PINRemoteLock *_lock;
  88. NSOperationQueue *_concurrentOperationQueue;
  89. NSOperationQueue *_urlSessionTaskQueue;
  90. // Necesarry to have a strong reference to _defaultAlternateRepresentationProvider because _alternateRepProvider is __weak
  91. PINAlternateRepresentationProvider *_defaultAlternateRepresentationProvider;
  92. __weak PINAlternateRepresentationProvider *_alternateRepProvider;
  93. }
  94. @property (nonatomic, strong) id<PINRemoteImageCaching> cache;
  95. @property (nonatomic, strong) PINURLSessionManager *sessionManager;
  96. @property (nonatomic, assign) NSTimeInterval timeout;
  97. @property (nonatomic, strong) NSMutableDictionary <NSString *, __kindof PINRemoteImageTask *> *tasks;
  98. @property (nonatomic, strong) NSHashTable <NSUUID *> *canceledTasks;
  99. @property (nonatomic, strong) NSArray <NSNumber *> *progressThresholds;
  100. @property (nonatomic, assign) BOOL shouldBlurProgressive;
  101. @property (nonatomic, assign) CGSize maxProgressiveRenderSize;
  102. @property (nonatomic, assign) NSTimeInterval estimatedRemainingTimeThreshold;
  103. @property (nonatomic, strong) dispatch_queue_t callbackQueue;
  104. @property (nonatomic, strong) NSOperationQueue *concurrentOperationQueue;
  105. @property (nonatomic, strong) NSOperationQueue *urlSessionTaskQueue;
  106. @property (nonatomic, strong) NSMutableArray <PINTaskQOS *> *taskQOS;
  107. @property (nonatomic, assign) float highQualityBPSThreshold;
  108. @property (nonatomic, assign) float lowQualityBPSThreshold;
  109. @property (nonatomic, assign) BOOL shouldUpgradeLowQualityImages;
  110. @property (nonatomic, copy) PINRemoteImageManagerAuthenticationChallenge authenticationChallengeHandler;
  111. #if DEBUG
  112. @property (nonatomic, assign) float currentBPS;
  113. @property (nonatomic, assign) BOOL overrideBPS;
  114. @property (nonatomic, assign) NSUInteger totalDownloads;
  115. #endif
  116. @end
  117. #pragma mark PINRemoteImageManager
  118. @implementation PINRemoteImageManager
  119. static PINRemoteImageManager *sharedImageManager = nil;
  120. static dispatch_once_t sharedDispatchToken;
  121. + (BOOL)supportsQOS
  122. {
  123. static dispatch_once_t onceToken;
  124. static BOOL supportsQOS;
  125. dispatch_once(&onceToken, ^{
  126. supportsQOS = [NSOperation instancesRespondToSelector:@selector(setQualityOfService:)];
  127. });
  128. return supportsQOS;
  129. }
  130. + (instancetype)sharedImageManager
  131. {
  132. dispatch_once(&sharedDispatchToken, ^{
  133. sharedImageManager = [[[self class] alloc] init];
  134. });
  135. return sharedImageManager;
  136. }
  137. + (void)setSharedImageManagerWithConfiguration:(NSURLSessionConfiguration *)configuration
  138. {
  139. NSAssert(sharedImageManager == nil, @"sharedImageManager singleton is already configured");
  140. dispatch_once(&sharedDispatchToken, ^{
  141. sharedImageManager = [[[self class] alloc] initWithSessionConfiguration:configuration];
  142. });
  143. }
  144. - (instancetype)init
  145. {
  146. return [self initWithSessionConfiguration:nil];
  147. }
  148. - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration
  149. {
  150. return [self initWithSessionConfiguration:configuration alternativeRepresentationProvider:nil];
  151. }
  152. - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration alternativeRepresentationProvider:(id <PINRemoteImageManagerAlternateRepresentationProvider>)alternateRepProvider
  153. {
  154. return [self initWithSessionConfiguration:configuration alternativeRepresentationProvider:alternateRepProvider imageCache:nil];
  155. }
  156. - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration alternativeRepresentationProvider:(nullable id <PINRemoteImageManagerAlternateRepresentationProvider>)alternateRepProvider
  157. imageCache:(nullable id<PINRemoteImageCaching>)imageCache
  158. {
  159. if (self = [super init]) {
  160. if (imageCache) {
  161. self.cache = imageCache;
  162. } else {
  163. self.cache = [self defaultImageCache];
  164. }
  165. if (!configuration) {
  166. configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
  167. }
  168. _callbackQueue = dispatch_queue_create("PINRemoteImageManagerCallbackQueue", DISPATCH_QUEUE_CONCURRENT);
  169. _lock = [[PINRemoteLock alloc] initWithName:@"PINRemoteImageManager"];
  170. _concurrentOperationQueue = [[NSOperationQueue alloc] init];
  171. _concurrentOperationQueue.name = @"PINRemoteImageManager Concurrent Operation Queue";
  172. _concurrentOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
  173. if ([[self class] supportsQOS]) {
  174. _concurrentOperationQueue.qualityOfService = NSQualityOfServiceUtility;
  175. }
  176. _urlSessionTaskQueue = [[NSOperationQueue alloc] init];
  177. _urlSessionTaskQueue.name = @"PINRemoteImageManager Concurrent URL Session Task Queue";
  178. _urlSessionTaskQueue.maxConcurrentOperationCount = 10;
  179. self.sessionManager = [[PINURLSessionManager alloc] initWithSessionConfiguration:configuration];
  180. self.sessionManager.delegate = self;
  181. self.estimatedRemainingTimeThreshold = 0.1;
  182. self.timeout = PINRemoteImageManagerDefaultTimeout;
  183. _highQualityBPSThreshold = 500000;
  184. _lowQualityBPSThreshold = 50000; // approximately edge speeds
  185. _shouldUpgradeLowQualityImages = NO;
  186. _shouldBlurProgressive = YES;
  187. _maxProgressiveRenderSize = CGSizeMake(1024, 1024);
  188. self.tasks = [[NSMutableDictionary alloc] init];
  189. self.canceledTasks = [[NSHashTable alloc] initWithOptions:NSHashTableWeakMemory capacity:5];
  190. self.taskQOS = [[NSMutableArray alloc] initWithCapacity:5];
  191. if (alternateRepProvider == nil) {
  192. _defaultAlternateRepresentationProvider = [[PINAlternateRepresentationProvider alloc] init];
  193. alternateRepProvider = _defaultAlternateRepresentationProvider;
  194. }
  195. _alternateRepProvider = alternateRepProvider;
  196. }
  197. return self;
  198. }
  199. - (id<PINRemoteImageCaching>)defaultImageCache
  200. {
  201. #if USE_PINCACHE
  202. NSString * const kPINRemoteImageDiskCacheName = @"PINRemoteImageManagerCache";
  203. NSString * const kPINRemoteImageDiskCacheVersionKey = @"kPINRemoteImageDiskCacheVersionKey";
  204. const NSInteger kPINRemoteImageDiskCacheVersion = 1;
  205. NSUserDefaults *pinDefaults = [[NSUserDefaults alloc] init];
  206. NSString *cacheURL = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  207. if ([pinDefaults integerForKey:kPINRemoteImageDiskCacheVersionKey] != kPINRemoteImageDiskCacheVersion) {
  208. //remove the old version of the disk cache
  209. PINDiskCache *tempDiskCache = [[PINDiskCache alloc] initWithName:kPINRemoteImageDiskCacheName];
  210. [[NSFileManager defaultManager] removeItemAtURL:[tempDiskCache cacheURL] error:nil];
  211. [pinDefaults setInteger:kPINRemoteImageDiskCacheVersion forKey:kPINRemoteImageDiskCacheVersionKey];
  212. }
  213. return [[PINCache alloc] initWithName:kPINRemoteImageDiskCacheName rootPath:cacheURL serializer:^NSData * _Nonnull(id<NSCoding> _Nonnull object, NSString * _Nonnull key) {
  214. return (NSData *)object;
  215. } deserializer:^id<NSCoding> _Nonnull(NSData * _Nonnull data, NSString * _Nonnull key) {
  216. return data;
  217. } fileExtension:nil];
  218. #else
  219. return [[PINRemoteImageBasicCache alloc] init];
  220. #endif
  221. }
  222. - (void)lockOnMainThread
  223. {
  224. #if !DEBUG
  225. NSAssert(NO, @"lockOnMainThread should only be called for testing on debug builds!");
  226. #endif
  227. [_lock lock];
  228. }
  229. - (void)lock
  230. {
  231. NSAssert([NSThread isMainThread] == NO, @"lock should not be called from the main thread!");
  232. [_lock lock];
  233. }
  234. - (void)unlock
  235. {
  236. [_lock unlock];
  237. }
  238. - (void)setAuthenticationChallenge:(PINRemoteImageManagerAuthenticationChallenge)challengeBlock {
  239. __weak typeof(self) weakSelf = self;
  240. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  241. typeof(self) strongSelf = weakSelf;
  242. [strongSelf lock];
  243. strongSelf.authenticationChallengeHandler = challengeBlock;
  244. [strongSelf unlock];
  245. });
  246. }
  247. - (void)setMaxNumberOfConcurrentOperations:(NSInteger)maxNumberOfConcurrentOperations completion:(dispatch_block_t)completion
  248. {
  249. __weak typeof(self) weakSelf = self;
  250. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  251. typeof(self) strongSelf = weakSelf;
  252. [strongSelf lock];
  253. strongSelf.concurrentOperationQueue.maxConcurrentOperationCount = maxNumberOfConcurrentOperations;
  254. [strongSelf unlock];
  255. if (completion) {
  256. completion();
  257. }
  258. });
  259. }
  260. - (void)setMaxNumberOfConcurrentDownloads:(NSInteger)maxNumberOfConcurrentDownloads completion:(dispatch_block_t)completion
  261. {
  262. __weak typeof(self) weakSelf = self;
  263. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  264. typeof(self) strongSelf = weakSelf;
  265. [strongSelf lock];
  266. strongSelf.urlSessionTaskQueue.maxConcurrentOperationCount = maxNumberOfConcurrentDownloads;
  267. [strongSelf unlock];
  268. if (completion) {
  269. completion();
  270. }
  271. });
  272. }
  273. - (void)setEstimatedRemainingTimeThresholdForProgressiveDownloads:(NSTimeInterval)estimatedRemainingTimeThreshold completion:(dispatch_block_t)completion
  274. {
  275. __weak typeof(self) weakSelf = self;
  276. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  277. typeof(self) strongSelf = weakSelf;
  278. [strongSelf lock];
  279. strongSelf.estimatedRemainingTimeThreshold = estimatedRemainingTimeThreshold;
  280. [strongSelf unlock];
  281. if (completion) {
  282. completion();
  283. }
  284. });
  285. }
  286. - (void)setProgressThresholds:(NSArray *)progressThresholds completion:(dispatch_block_t)completion
  287. {
  288. __weak typeof(self) weakSelf = self;
  289. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  290. typeof(self) strongSelf = weakSelf;
  291. [strongSelf lock];
  292. strongSelf.progressThresholds = progressThresholds;
  293. [strongSelf unlock];
  294. if (completion) {
  295. completion();
  296. }
  297. });
  298. }
  299. - (void)setProgressiveRendersShouldBlur:(BOOL)shouldBlur completion:(nullable dispatch_block_t)completion
  300. {
  301. __weak typeof(self) weakSelf = self;
  302. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  303. typeof(self) strongSelf = weakSelf;
  304. [strongSelf lock];
  305. strongSelf.shouldBlurProgressive = shouldBlur;
  306. [strongSelf unlock];
  307. if (completion) {
  308. completion();
  309. }
  310. });
  311. }
  312. - (void)setProgressiveRendersMaxProgressiveRenderSize:(CGSize)maxProgressiveRenderSize completion:(nullable dispatch_block_t)completion
  313. {
  314. __weak typeof(self) weakSelf = self;
  315. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  316. typeof(self) strongSelf = weakSelf;
  317. [strongSelf lock];
  318. strongSelf.maxProgressiveRenderSize = maxProgressiveRenderSize;
  319. [strongSelf unlock];
  320. if (completion) {
  321. completion();
  322. }
  323. });
  324. }
  325. - (void)setHighQualityBPSThreshold:(float)highQualityBPSThreshold completion:(dispatch_block_t)completion
  326. {
  327. __weak typeof(self) weakSelf = self;
  328. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  329. typeof(self) strongSelf = weakSelf;
  330. [strongSelf lock];
  331. strongSelf.highQualityBPSThreshold = highQualityBPSThreshold;
  332. [strongSelf unlock];
  333. if (completion) {
  334. completion();
  335. }
  336. });
  337. }
  338. - (void)setLowQualityBPSThreshold:(float)lowQualityBPSThreshold completion:(dispatch_block_t)completion
  339. {
  340. __weak typeof(self) weakSelf = self;
  341. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  342. typeof(self) strongSelf = weakSelf;
  343. [strongSelf lock];
  344. strongSelf.lowQualityBPSThreshold = lowQualityBPSThreshold;
  345. [strongSelf unlock];
  346. if (completion) {
  347. completion();
  348. }
  349. });
  350. }
  351. - (void)setShouldUpgradeLowQualityImages:(BOOL)shouldUpgradeLowQualityImages completion:(dispatch_block_t)completion
  352. {
  353. __weak typeof(self) weakSelf = self;
  354. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  355. typeof(self) strongSelf = weakSelf;
  356. [strongSelf lock];
  357. strongSelf.shouldUpgradeLowQualityImages = shouldUpgradeLowQualityImages;
  358. [strongSelf unlock];
  359. if (completion) {
  360. completion();
  361. }
  362. });
  363. }
  364. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  365. completion:(PINRemoteImageManagerImageCompletion)completion
  366. {
  367. return [self downloadImageWithURL:url
  368. options:PINRemoteImageManagerDownloadOptionsNone
  369. completion:completion];
  370. }
  371. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  372. options:(PINRemoteImageManagerDownloadOptions)options
  373. completion:(PINRemoteImageManagerImageCompletion)completion
  374. {
  375. return [self downloadImageWithURL:url
  376. options:options
  377. progressImage:nil
  378. completion:completion];
  379. }
  380. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  381. options:(PINRemoteImageManagerDownloadOptions)options
  382. progressImage:(PINRemoteImageManagerImageCompletion)progressImage
  383. completion:(PINRemoteImageManagerImageCompletion)completion
  384. {
  385. return [self downloadImageWithURL:url
  386. options:options
  387. priority:PINRemoteImageManagerPriorityMedium
  388. processorKey:nil
  389. processor:nil
  390. progressImage:progressImage
  391. progressDownload:nil
  392. completion:completion
  393. inputUUID:nil];
  394. }
  395. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  396. options:(PINRemoteImageManagerDownloadOptions)options
  397. progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
  398. completion:(PINRemoteImageManagerImageCompletion)completion
  399. {
  400. return [self downloadImageWithURL:url
  401. options:options
  402. priority:PINRemoteImageManagerPriorityMedium
  403. processorKey:nil
  404. processor:nil
  405. progressImage:nil
  406. progressDownload:progressDownload
  407. completion:completion
  408. inputUUID:nil];
  409. }
  410. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  411. options:(PINRemoteImageManagerDownloadOptions)options
  412. progressImage:(PINRemoteImageManagerImageCompletion)progressImage
  413. progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
  414. completion:(PINRemoteImageManagerImageCompletion)completion
  415. {
  416. return [self downloadImageWithURL:url
  417. options:options
  418. priority:PINRemoteImageManagerPriorityMedium
  419. processorKey:nil
  420. processor:nil
  421. progressImage:progressImage
  422. progressDownload:progressDownload
  423. completion:completion
  424. inputUUID:nil];
  425. }
  426. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  427. options:(PINRemoteImageManagerDownloadOptions)options
  428. processorKey:(NSString *)processorKey
  429. processor:(PINRemoteImageManagerImageProcessor)processor
  430. completion:(PINRemoteImageManagerImageCompletion)completion
  431. {
  432. return [self downloadImageWithURL:url
  433. options:options
  434. priority:PINRemoteImageManagerPriorityMedium
  435. processorKey:processorKey
  436. processor:processor
  437. progressImage:nil
  438. progressDownload:nil
  439. completion:completion
  440. inputUUID:nil];
  441. }
  442. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  443. options:(PINRemoteImageManagerDownloadOptions)options
  444. processorKey:(NSString *)processorKey
  445. processor:(PINRemoteImageManagerImageProcessor)processor
  446. progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
  447. completion:(PINRemoteImageManagerImageCompletion)completion
  448. {
  449. return [self downloadImageWithURL:url
  450. options:options
  451. priority:PINRemoteImageManagerPriorityMedium
  452. processorKey:processorKey
  453. processor:processor
  454. progressImage:nil
  455. progressDownload:progressDownload
  456. completion:completion
  457. inputUUID:nil];
  458. }
  459. - (NSUUID *)downloadImageWithURL:(NSURL *)url
  460. options:(PINRemoteImageManagerDownloadOptions)options
  461. priority:(PINRemoteImageManagerPriority)priority
  462. processorKey:(NSString *)processorKey
  463. processor:(PINRemoteImageManagerImageProcessor)processor
  464. progressImage:(PINRemoteImageManagerImageCompletion)progressImage
  465. progressDownload:(PINRemoteImageManagerProgressDownload)progressDownload
  466. completion:(PINRemoteImageManagerImageCompletion)completion
  467. inputUUID:(NSUUID *)UUID
  468. {
  469. 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");
  470. Class taskClass;
  471. if (processor && processorKey.length > 0) {
  472. taskClass = [PINRemoteImageProcessorTask class];
  473. } else {
  474. taskClass = [PINRemoteImageDownloadTask class];
  475. }
  476. NSString *key = [self cacheKeyForURL:url processorKey:processorKey];
  477. if (url == nil) {
  478. [self earlyReturnWithOptions:options url:nil key:key object:nil completion:completion];
  479. return nil;
  480. }
  481. NSAssert([url isKindOfClass:[NSURL class]], @"url must be of type NSURL, if it's an NSString, we'll try to correct");
  482. if ([url isKindOfClass:[NSString class]]) {
  483. url = [NSURL URLWithString:(NSString *)url];
  484. }
  485. if (UUID == nil) {
  486. UUID = [NSUUID UUID];
  487. }
  488. if ((options & PINRemoteImageManagerDownloadOptionsIgnoreCache) == 0) {
  489. //Check to see if the image is in memory cache and we're on the main thread.
  490. //If so, special case this to avoid flashing the UI
  491. id object = [self.cache objectFromMemoryForKey:key];
  492. if (object) {
  493. if ([self earlyReturnWithOptions:options url:url key:key object:object completion:completion]) {
  494. return nil;
  495. }
  496. }
  497. }
  498. if ([url.scheme isEqualToString:@"data"]) {
  499. NSData *data = [NSData dataWithContentsOfURL:url];
  500. if (data) {
  501. if ([self earlyReturnWithOptions:options url:url key:key object:data completion:completion]) {
  502. return nil;
  503. }
  504. }
  505. }
  506. __weak typeof(self) weakSelf = self;
  507. [_concurrentOperationQueue pin_addOperationWithQueuePriority:priority block:^
  508. {
  509. typeof(self) strongSelf = weakSelf;
  510. [strongSelf lock];
  511. //check canceled tasks first
  512. if ([strongSelf.canceledTasks containsObject:UUID]) {
  513. PINLog(@"skipping starting %@ because it was canceled.", UUID);
  514. [strongSelf unlock];
  515. return;
  516. }
  517. PINRemoteImageTask *task = [strongSelf.tasks objectForKey:key];
  518. BOOL taskExisted = NO;
  519. if (task == nil) {
  520. task = [[taskClass alloc] init];
  521. PINLog(@"Task does not exist creating with key: %@, URL: %@, UUID: %@, task: %p", key, url, UUID, task);
  522. #if PINRemoteImageLogging
  523. task.key = key;
  524. #endif
  525. } else {
  526. taskExisted = YES;
  527. PINLog(@"Task exists, attaching with key: %@, URL: %@, UUID: %@, task: %@", key, url, UUID, task);
  528. }
  529. [task addCallbacksWithCompletionBlock:completion progressImageBlock:progressImage progressDownloadBlock:progressDownload withUUID:UUID];
  530. [strongSelf.tasks setObject:task forKey:key];
  531. BlockAssert(taskClass == [task class], @"Task class should be the same!");
  532. [strongSelf unlock];
  533. if (taskExisted == NO) {
  534. [strongSelf.concurrentOperationQueue pin_addOperationWithQueuePriority:priority block:^
  535. {
  536. typeof(self) strongSelf = weakSelf;
  537. [strongSelf objectForKey:key options:options completion:^(BOOL found, BOOL valid, PINImage *image, id alternativeRepresentation) {
  538. if (found) {
  539. if (valid) {
  540. typeof(self) strongSelf = weakSelf;
  541. [strongSelf callCompletionsWithKey:key image:image alternativeRepresentation:alternativeRepresentation cached:YES error:nil finalized:YES];
  542. } else {
  543. //Remove completion and try again
  544. typeof(self) strongSelf = weakSelf;
  545. [strongSelf lock];
  546. PINRemoteImageTask *task = [strongSelf.tasks objectForKey:key];
  547. [task removeCallbackWithUUID:UUID];
  548. if (task.callbackBlocks.count == 0) {
  549. [strongSelf.tasks removeObjectForKey:key];
  550. }
  551. [strongSelf unlock];
  552. //Skip early check
  553. [strongSelf downloadImageWithURL:url
  554. options:options | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck
  555. priority:priority
  556. processorKey:processorKey
  557. processor:processor
  558. progressImage:(PINRemoteImageManagerImageCompletion)progressImage
  559. progressDownload:nil
  560. completion:completion
  561. inputUUID:UUID];
  562. }
  563. } else {
  564. if ([taskClass isSubclassOfClass:[PINRemoteImageProcessorTask class]]) {
  565. //continue processing
  566. [strongSelf downloadImageWithURL:url
  567. options:options
  568. priority:priority
  569. key:key
  570. processor:processor
  571. UUID:UUID];
  572. } else if ([taskClass isSubclassOfClass:[PINRemoteImageDownloadTask class]]) {
  573. //continue downloading
  574. [strongSelf downloadImageWithURL:url
  575. options:options
  576. priority:priority
  577. key:key
  578. progressImage:progressImage
  579. UUID:UUID];
  580. }
  581. }
  582. }];
  583. }];
  584. }
  585. }];
  586. return UUID;
  587. }
  588. - (void)downloadImageWithURL:(NSURL *)url
  589. options:(PINRemoteImageManagerDownloadOptions)options
  590. priority:(PINRemoteImageManagerPriority)priority
  591. key:(NSString *)key
  592. processor:(PINRemoteImageManagerImageProcessor)processor
  593. UUID:(NSUUID *)UUID
  594. {
  595. PINRemoteImageProcessorTask *task = nil;
  596. [self lock];
  597. task = [self.tasks objectForKey:key];
  598. //check processing task still exists and download hasn't been started for another task
  599. if (task == nil || task.downloadTaskUUID != nil) {
  600. [self unlock];
  601. return;
  602. }
  603. __weak typeof(self) weakSelf = self;
  604. NSUUID *downloadTaskUUID = [self downloadImageWithURL:url
  605. options:options | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck
  606. completion:^(PINRemoteImageManagerResult *result)
  607. {
  608. typeof(self) strongSelf = weakSelf;
  609. NSUInteger processCost = 0;
  610. NSError *error = result.error;
  611. PINRemoteImageProcessorTask *task = nil;
  612. [strongSelf lock];
  613. task = [strongSelf.tasks objectForKey:key];
  614. [strongSelf unlock];
  615. //check processing task still exists
  616. if (task == nil) {
  617. return;
  618. }
  619. if (result.image && error == nil) {
  620. //If completionBlocks.count == 0, we've canceled before we were even able to start.
  621. PINImage *image = processor(result, &processCost);
  622. if (image == nil) {
  623. error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
  624. code:PINRemoteImageManagerErrorFailedToProcessImage
  625. userInfo:nil];
  626. }
  627. [strongSelf callCompletionsWithKey:key image:image alternativeRepresentation:nil cached:NO error:error finalized:NO];
  628. if (error == nil) {
  629. BOOL saveAsJPEG = (options & PINRemoteImageManagerSaveProcessedImageAsJPEG) != 0;
  630. NSData *diskData = nil;
  631. if (saveAsJPEG) {
  632. diskData = PINImageJPEGRepresentation(image, 1.0);
  633. } else {
  634. diskData = PINImagePNGRepresentation(image);
  635. }
  636. [strongSelf materializeAndCacheObject:image cacheInDisk:diskData additionalCost:processCost key:key options:options outImage:nil outAltRep:nil];
  637. }
  638. [strongSelf callCompletionsWithKey:key image:image alternativeRepresentation:nil cached:NO error:error finalized:YES];
  639. } else {
  640. if (error == nil) {
  641. error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
  642. code:PINRemoteImageManagerErrorFailedToFetchImageForProcessing
  643. userInfo:nil];
  644. }
  645. [strongSelf callCompletionsWithKey:key image:nil alternativeRepresentation:nil cached:NO error:error finalized:YES];
  646. }
  647. }];
  648. task.downloadTaskUUID = downloadTaskUUID;
  649. [self unlock];
  650. }
  651. - (void)downloadImageWithURL:(NSURL *)url
  652. options:(PINRemoteImageManagerDownloadOptions)options
  653. priority:(PINRemoteImageManagerPriority)priority
  654. key:(NSString *)key
  655. progressImage:(PINRemoteImageManagerImageCompletion)progressImage
  656. UUID:(NSUUID *)UUID
  657. {
  658. [self lock];
  659. PINRemoteImageDownloadTask *task = [self.tasks objectForKey:key];
  660. if (task.urlSessionTaskOperation == nil && task.callbackBlocks.count > 0 && task.numberOfRetries == 0) {
  661. //If completionBlocks.count == 0, we've canceled before we were even able to start.
  662. CFTimeInterval startTime = CACurrentMediaTime();
  663. PINDataTaskOperation *urlSessionTaskOperation = [self sessionTaskWithURL:url key:key options:options priority:priority];
  664. task.urlSessionTaskOperation = urlSessionTaskOperation;
  665. task.sessionTaskStartTime = startTime;
  666. }
  667. [self unlock];
  668. }
  669. - (BOOL)earlyReturnWithOptions:(PINRemoteImageManagerDownloadOptions)options url:(NSURL *)url key:(NSString *)key object:(id)object completion:(PINRemoteImageManagerImageCompletion)completion
  670. {
  671. PINImage *image = nil;
  672. id alternativeRepresentation = nil;
  673. PINRemoteImageResultType resultType = PINRemoteImageResultTypeNone;
  674. BOOL allowEarlyReturn = !(PINRemoteImageManagerDownloadOptionsSkipEarlyCheck & options);
  675. if (url != nil && object != nil) {
  676. resultType = PINRemoteImageResultTypeMemoryCache;
  677. [self materializeAndCacheObject:object key:key options:options outImage:&image outAltRep:&alternativeRepresentation];
  678. }
  679. if (completion && ((image || alternativeRepresentation) || (url == nil))) {
  680. //If we're on the main thread, special case to call completion immediately
  681. NSError *error = nil;
  682. if (!url) {
  683. error = [NSError errorWithDomain:NSURLErrorDomain
  684. code:NSURLErrorUnsupportedURL
  685. userInfo:@{ NSLocalizedDescriptionKey : @"unsupported URL" }];
  686. }
  687. if (allowEarlyReturn && [NSThread isMainThread]) {
  688. completion([PINRemoteImageManagerResult imageResultWithImage:image
  689. alternativeRepresentation:alternativeRepresentation
  690. requestLength:0
  691. error:error
  692. resultType:resultType
  693. UUID:nil]);
  694. } else {
  695. dispatch_async(self.callbackQueue, ^{
  696. completion([PINRemoteImageManagerResult imageResultWithImage:image
  697. alternativeRepresentation:alternativeRepresentation
  698. requestLength:0
  699. error:error
  700. resultType:resultType
  701. UUID:nil]);
  702. });
  703. }
  704. return YES;
  705. }
  706. return NO;
  707. }
  708. - (PINDataTaskOperation *)sessionTaskWithURL:(NSURL *)URL
  709. key:(NSString *)key
  710. options:(PINRemoteImageManagerDownloadOptions)options
  711. priority:(PINRemoteImageManagerPriority)priority
  712. {
  713. __weak typeof(self) weakSelf = self;
  714. return [self downloadDataWithURL:URL
  715. key:key
  716. priority:priority
  717. completion:^(NSData *data, NSError *error)
  718. {
  719. [_concurrentOperationQueue pin_addOperationWithQueuePriority:priority block:^
  720. {
  721. typeof(self) strongSelf = weakSelf;
  722. NSError *remoteImageError = error;
  723. PINImage *image = nil;
  724. id alternativeRepresentation = nil;
  725. if (remoteImageError && [[self class] retriableError:remoteImageError]) {
  726. //attempt to retry after delay
  727. BOOL retry = NO;
  728. NSUInteger newNumberOfRetries = 0;
  729. [strongSelf lock];
  730. PINRemoteImageDownloadTask *task = [self.tasks objectForKey:key];
  731. if (task.numberOfRetries < PINRemoteImageMaxRetries) {
  732. retry = YES;
  733. newNumberOfRetries = ++task.numberOfRetries;
  734. // Clear out the exsiting progress image or else new data from retry will be appended
  735. task.progressImage = nil;
  736. task.urlSessionTaskOperation = nil;
  737. }
  738. [strongSelf unlock];
  739. if (retry) {
  740. int64_t delay = powf(PINRemoteImageRetryDelayBase, newNumberOfRetries);
  741. PINLog(@"Retrying download of %@ in %d seconds.", URL, delay);
  742. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  743. typeof(self) strongSelf = weakSelf;
  744. [strongSelf lock];
  745. PINRemoteImageDownloadTask *task = [strongSelf.tasks objectForKey:key];
  746. if (task.urlSessionTaskOperation == nil && task.callbackBlocks.count > 0) {
  747. //If completionBlocks.count == 0, we've canceled before we were even able to start.
  748. PINDataTaskOperation *urlSessionTaskOperation = [strongSelf sessionTaskWithURL:URL key:key options:options priority:priority];
  749. task.urlSessionTaskOperation = urlSessionTaskOperation;
  750. }
  751. [strongSelf unlock];
  752. });
  753. return;
  754. }
  755. } else if (remoteImageError == nil) {
  756. //stores the object in the caches
  757. [strongSelf materializeAndCacheObject:data cacheInDisk:data additionalCost:0 key:key options:options outImage:&image outAltRep:&alternativeRepresentation];
  758. }
  759. if (error == nil && image == nil && alternativeRepresentation == nil) {
  760. remoteImageError = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
  761. code:PINRemoteImageManagerErrorFailedToDecodeImage
  762. userInfo:nil];
  763. }
  764. [strongSelf callCompletionsWithKey:key image:image alternativeRepresentation:alternativeRepresentation cached:NO error:remoteImageError finalized:YES];
  765. }];
  766. }];
  767. }
  768. + (BOOL)retriableError:(NSError *)remoteImageError
  769. {
  770. if ([remoteImageError.domain isEqualToString:PINURLErrorDomain]) {
  771. return remoteImageError.code >= 500;
  772. } else if ([remoteImageError.domain isEqualToString:NSURLErrorDomain] && remoteImageError.code == NSURLErrorUnsupportedURL) {
  773. return NO;
  774. } else if ([remoteImageError.domain isEqualToString:PINRemoteImageManagerErrorDomain]) {
  775. return NO;
  776. }
  777. return YES;
  778. }
  779. - (PINDataTaskOperation *)downloadDataWithURL:(NSURL *)url
  780. key:(NSString *)key
  781. priority:(PINRemoteImageManagerPriority)priority
  782. completion:(PINRemoteImageManagerDataCompletion)completion
  783. {
  784. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
  785. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  786. timeoutInterval:self.timeout];
  787. [NSURLProtocol setProperty:key forKey:PINRemoteImageCacheKey inRequest:request];
  788. __weak typeof(self) weakSelf = self;
  789. PINDataTaskOperation *dataTaskOperation = [PINDataTaskOperation dataTaskOperationWithSessionManager:self.sessionManager
  790. request:request
  791. completionHandler:^(NSURLResponse *response, NSError *error)
  792. {
  793. typeof(self) strongSelf = weakSelf;
  794. #if DEBUG
  795. [strongSelf lock];
  796. strongSelf.totalDownloads++;
  797. [strongSelf unlock];
  798. #endif
  799. #if PINRemoteImageLogging
  800. if (error && error.code != NSURLErrorCancelled) {
  801. PINLog(@"Failed downloading image: %@ with error: %@", url, error);
  802. } else if (error == nil && response.expectedContentLength == 0) {
  803. PINLog(@"image is empty at URL: %@", url);
  804. } else {
  805. PINLog(@"Finished downloading image: %@", url);
  806. }
  807. #endif
  808. if (error.code != NSURLErrorCancelled) {
  809. [strongSelf lock];
  810. PINRemoteImageDownloadTask *task = [strongSelf.tasks objectForKey:key];
  811. NSData *data = task.progressImage.data;
  812. [strongSelf unlock];
  813. if (error == nil && data == nil) {
  814. error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
  815. code:PINRemoteImageManagerErrorImageEmpty
  816. userInfo:nil];
  817. }
  818. completion(data, error);
  819. }
  820. }];
  821. if ([dataTaskOperation.dataTask respondsToSelector:@selector(setPriority:)]) {
  822. dataTaskOperation.dataTask.priority = dataTaskPriorityWithImageManagerPriority(priority);
  823. }
  824. dataTaskOperation.queuePriority = operationPriorityWithImageManagerPriority(priority);
  825. [self.urlSessionTaskQueue addOperation:dataTaskOperation];
  826. return dataTaskOperation;
  827. }
  828. - (void)callCompletionsWithKey:(NSString *)key image:(PINImage *)image alternativeRepresentation:(id)alternativeRepresentation cached:(BOOL)cached error:(NSError *)error finalized:(BOOL)finalized
  829. {
  830. [self lock];
  831. PINRemoteImageDownloadTask *task = [self.tasks objectForKey:key];
  832. [task callCompletionsWithQueue:self.callbackQueue remove:!finalized withImage:image alternativeRepresentation:alternativeRepresentation cached:cached error:error];
  833. if (finalized) {
  834. [self.tasks removeObjectForKey:key];
  835. }
  836. [self unlock];
  837. }
  838. #pragma mark - Prefetching
  839. - (NSArray<NSUUID *> *)prefetchImagesWithURLs:(NSArray <NSURL *> *)urls
  840. {
  841. return [self prefetchImagesWithURLs:urls options:PINRemoteImageManagerDownloadOptionsNone | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck];
  842. }
  843. - (NSArray<NSUUID *> *)prefetchImagesWithURLs:(NSArray <NSURL *> *)urls options:(PINRemoteImageManagerDownloadOptions)options
  844. {
  845. NSMutableArray *tasks = [NSMutableArray arrayWithCapacity:urls.count];
  846. for (NSURL *url in urls) {
  847. NSUUID *task = [self prefetchImageWithURL:url options:options];
  848. if (task != nil) {
  849. [tasks addObject:task];
  850. }
  851. }
  852. return tasks;
  853. }
  854. - (NSUUID *)prefetchImageWithURL:(NSURL *)url
  855. {
  856. return [self prefetchImageWithURL:url options:PINRemoteImageManagerDownloadOptionsNone | PINRemoteImageManagerDownloadOptionsSkipEarlyCheck];
  857. }
  858. - (NSUUID *)prefetchImageWithURL:(NSURL *)url options:(PINRemoteImageManagerDownloadOptions)options
  859. {
  860. return [self downloadImageWithURL:url
  861. options:options
  862. priority:PINRemoteImageManagerPriorityVeryLow
  863. processorKey:nil
  864. processor:nil
  865. progressImage:nil
  866. progressDownload:nil
  867. completion:nil
  868. inputUUID:nil];
  869. }
  870. #pragma mark - Cancelation & Priority
  871. - (void)cancelTaskWithUUID:(NSUUID *)UUID
  872. {
  873. if (UUID == nil) {
  874. return;
  875. }
  876. PINLog(@"Attempting to cancel UUID: %@", UUID);
  877. __weak typeof(self) weakSelf = self;
  878. [_concurrentOperationQueue pin_addOperationWithQueuePriority:PINRemoteImageManagerPriorityHigh block:^
  879. {
  880. typeof(self) strongSelf = weakSelf;
  881. //find the task associated with the UUID. This might be spead up by storing a mapping of UUIDs to tasks
  882. [strongSelf lock];
  883. __block PINRemoteImageTask *taskToEvaluate = nil;
  884. __block NSString *taskKey = nil;
  885. [strongSelf.tasks enumerateKeysAndObjectsUsingBlock:^(NSString *key, PINRemoteImageTask *task, BOOL *stop) {
  886. if (task.callbackBlocks[UUID]) {
  887. taskToEvaluate = task;
  888. taskKey = key;
  889. *stop = YES;
  890. }
  891. }];
  892. if (taskToEvaluate == nil) {
  893. //maybe task hasn't been added to task list yet, add it to canceled tasks.
  894. //there's no need to ever remove a UUID from canceledTasks because it is weak.
  895. [strongSelf.canceledTasks addObject:UUID];
  896. }
  897. if ([taskToEvaluate cancelWithUUID:UUID manager:strongSelf]) {
  898. [strongSelf.tasks removeObjectForKey:taskKey];
  899. }
  900. [strongSelf unlock];
  901. }];
  902. }
  903. - (void)setPriority:(PINRemoteImageManagerPriority)priority ofTaskWithUUID:(NSUUID *)UUID
  904. {
  905. if (UUID == nil) {
  906. return;
  907. }
  908. PINLog(@"Setting priority of UUID: %@ priority: %lu", UUID, (unsigned long)priority);
  909. __weak typeof(self) weakSelf = self;
  910. [_concurrentOperationQueue pin_addOperationWithQueuePriority:PINRemoteImageManagerPriorityHigh block:^{
  911. typeof(self) strongSelf = weakSelf;
  912. [strongSelf lock];
  913. PINRemoteImageTask *taskToEvaluate = nil;
  914. for (NSString *key in [strongSelf.tasks allKeys]) {
  915. PINRemoteImageTask *task = [strongSelf.tasks objectForKey:key];
  916. for (NSUUID *blockUUID in [task.callbackBlocks allKeys]) {
  917. if ([blockUUID isEqual:UUID]) {
  918. taskToEvaluate = task;
  919. break;
  920. }
  921. }
  922. }
  923. [taskToEvaluate setPriority:priority];
  924. [strongSelf unlock];
  925. }];
  926. }
  927. - (void)setProgressImageCallback:(nullable PINRemoteImageManagerImageCompletion)progressImageCallback ofTaskWithUUID:(nonnull NSUUID *)UUID
  928. {
  929. if (UUID == nil) {
  930. return;
  931. }
  932. PINLog(@"setting progress block of UUID: %@ progressBlock: %@", UUID, progressImageCallback);
  933. __weak typeof(self) weakSelf = self;
  934. [_concurrentOperationQueue pin_addOperationWithQueuePriority:PINRemoteImageManagerPriorityHigh block:^{
  935. typeof(self) strongSelf = weakSelf;
  936. [strongSelf lock];
  937. for (NSString *key in [strongSelf.tasks allKeys]) {
  938. PINRemoteImageTask *task = [strongSelf.tasks objectForKey:key];
  939. for (NSUUID *blockUUID in [task.callbackBlocks allKeys]) {
  940. if ([blockUUID isEqual:UUID]) {
  941. if ([task isKindOfClass:[PINRemoteImageDownloadTask class]]) {
  942. PINRemoteImageCallbacks *callbacks = task.callbackBlocks[blockUUID];
  943. callbacks.progressImageBlock = progressImageCallback;
  944. }
  945. break;
  946. }
  947. }
  948. }
  949. [strongSelf unlock];
  950. }];
  951. }
  952. #pragma mark - Caching
  953. - (void)imageFromCacheWithCacheKey:(NSString *)cacheKey
  954. completion:(PINRemoteImageManagerImageCompletion)completion
  955. {
  956. [self imageFromCacheWithCacheKey:cacheKey options:PINRemoteImageManagerDownloadOptionsNone completion:completion];
  957. }
  958. - (void)imageFromCacheWithCacheKey:(NSString *)cacheKey
  959. options:(PINRemoteImageManagerDownloadOptions)options
  960. completion:(PINRemoteImageManagerImageCompletion)completion
  961. {
  962. CFTimeInterval requestTime = CACurrentMediaTime();
  963. if ((PINRemoteImageManagerDownloadOptionsSkipEarlyCheck & options) == NO && [NSThread isMainThread]) {
  964. PINRemoteImageManagerResult *result = [self synchronousImageFromCacheWithCacheKey:cacheKey options:options];
  965. if (result.image && result.error) {
  966. completion((result));
  967. return;
  968. }
  969. }
  970. [self objectForKey:cacheKey options:options completion:^(BOOL found, BOOL valid, PINImage *image, id alternativeRepresentation) {
  971. NSError *error = nil;
  972. if (valid == NO) {
  973. error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
  974. code:PINRemoteImageManagerErrorInvalidItemInCache
  975. userInfo:nil];
  976. }
  977. dispatch_async(self.callbackQueue, ^{
  978. completion([PINRemoteImageManagerResult imageResultWithImage:image
  979. alternativeRepresentation:alternativeRepresentation
  980. requestLength:CACurrentMediaTime() - requestTime
  981. error:error
  982. resultType:PINRemoteImageResultTypeCache
  983. UUID:nil]);
  984. });
  985. }];
  986. }
  987. - (PINRemoteImageManagerResult *)synchronousImageFromCacheWithCacheKey:(NSString *)cacheKey options:(PINRemoteImageManagerDownloadOptions)options
  988. {
  989. CFTimeInterval requestTime = CACurrentMediaTime();
  990. id object = [self.cache objectFromMemoryForKey:cacheKey];
  991. PINImage *image;
  992. id alternativeRepresentation;
  993. NSError *error = nil;
  994. if (object == nil) {
  995. image = nil;
  996. alternativeRepresentation = nil;
  997. } else if ([self materializeAndCacheObject:object key:cacheKey options:options outImage:&image outAltRep:&alternativeRepresentation] == NO) {
  998. error = [NSError errorWithDomain:PINRemoteImageManagerErrorDomain
  999. code:PINRemoteImageManagerErrorInvalidItemInCache
  1000. userInfo:nil];
  1001. }
  1002. return [PINRemoteImageManagerResult imageResultWithImage:image
  1003. alternativeRepresentation:alternativeRepresentation
  1004. requestLength:CACurrentMediaTime() - requestTime
  1005. error:error
  1006. resultType:PINRemoteImageResultTypeMemoryCache
  1007. UUID:nil];
  1008. }
  1009. #pragma mark - Session Task Blocks
  1010. - (void)didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge forTask:(NSURLSessionTask *)task completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
  1011. [self lock];
  1012. if (self.authenticationChallengeHandler) {
  1013. self.authenticationChallengeHandler(task, challenge, ^(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential){
  1014. completionHandler(disposition, credential);
  1015. });
  1016. } else {
  1017. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1018. }
  1019. [self unlock];
  1020. }
  1021. - (void)didReceiveData:(NSData *)data forTask:(NSURLSessionDataTask *)dataTask
  1022. {
  1023. [self lock];
  1024. NSString *cacheKey = [NSURLProtocol propertyForKey:PINRemoteImageCacheKey inRequest:dataTask.originalRequest];
  1025. PINRemoteImageDownloadTask *task = [self.tasks objectForKey:cacheKey];
  1026. if (task.progressImage == nil) {
  1027. task.progressImage = [[PINProgressiveImage alloc] init];
  1028. task.progressImage.startTime = task.sessionTaskStartTime;
  1029. task.progressImage.estimatedRemainingTimeThreshold = self.estimatedRemainingTimeThreshold;
  1030. if (self.progressThresholds) {
  1031. task.progressImage.progressThresholds = self.progressThresholds;
  1032. }
  1033. }
  1034. PINProgressiveImage *progressiveImage = task.progressImage;
  1035. BOOL hasProgressBlocks = task.hasProgressBlocks;
  1036. BOOL shouldBlur = self.shouldBlurProgressive;
  1037. CGSize maxProgressiveRenderSize = self.maxProgressiveRenderSize;
  1038. [task callProgressDownloadWithQueue:self.callbackQueue completedBytes:dataTask.countOfBytesReceived totalBytes:dataTask.countOfBytesExpectedToReceive];
  1039. [self unlock];
  1040. [progressiveImage updateProgressiveImageWithData:data expectedNumberOfBytes:[dataTask countOfBytesExpectedToReceive]];
  1041. if (hasProgressBlocks && [NSOperation instancesRespondToSelector:@selector(qualityOfService)]) {
  1042. __weak typeof(self) weakSelf = self;
  1043. [_concurrentOperationQueue pin_addOperationWithQueuePriority:PINRemoteImageManagerPriorityLow block:^{
  1044. typeof(self) strongSelf = weakSelf;
  1045. CGFloat renderedImageQuality = 1.0;
  1046. PINImage *progressImage = [progressiveImage currentImageBlurred:shouldBlur maxProgressiveRenderSize:maxProgressiveRenderSize renderedImageQuality:&renderedImageQuality];
  1047. if (progressImage) {
  1048. [strongSelf lock];
  1049. PINRemoteImageDownloadTask *task = strongSelf.tasks[cacheKey];
  1050. [task callProgressImageWithQueue:strongSelf.callbackQueue withImage:progressImage renderedImageQuality:renderedImageQuality];
  1051. [strongSelf unlock];
  1052. }
  1053. }];
  1054. }
  1055. }
  1056. - (void)didCompleteTask:(NSURLSessionTask *)task withError:(NSError *)error
  1057. {
  1058. if (error == nil && [task isKindOfClass:[NSURLSessionDataTask class]]) {
  1059. NSURLSessionDataTask *dataTask = (NSURLSessionDataTask *)task;
  1060. [self lock];
  1061. NSString *cacheKey = [NSURLProtocol propertyForKey:PINRemoteImageCacheKey inRequest:dataTask.originalRequest];
  1062. PINRemoteImageDownloadTask *task = [self.tasks objectForKey:cacheKey];
  1063. task.sessionTaskEndTime = CACurrentMediaTime();
  1064. CFTimeInterval taskLength = task.sessionTaskEndTime - task.sessionTaskStartTime;
  1065. [self unlock];
  1066. float bytesPerSecond = dataTask.countOfBytesReceived / taskLength;
  1067. [self addTaskBPS:bytesPerSecond endDate:[NSDate date]];
  1068. }
  1069. }
  1070. #pragma mark - QOS
  1071. - (float)currentBytesPerSecond
  1072. {
  1073. [self lock];
  1074. #if DEBUG
  1075. if (self.overrideBPS) {
  1076. float currentBPS = self.currentBPS;
  1077. [self unlock];
  1078. return currentBPS;
  1079. }
  1080. #endif
  1081. const NSTimeInterval validThreshold = 60.0;
  1082. __block NSUInteger count = 0;
  1083. __block float bps = 0;
  1084. __block BOOL valid = NO;
  1085. NSDate *threshold = [NSDate dateWithTimeIntervalSinceNow:-validThreshold];
  1086. [self.taskQOS enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(PINTaskQOS *taskQOS, NSUInteger idx, BOOL *stop) {
  1087. if ([taskQOS.endDate compare:threshold] == NSOrderedAscending) {
  1088. *stop = YES;
  1089. return;
  1090. }
  1091. valid = YES;
  1092. count++;
  1093. bps += taskQOS.bytesPerSecond;
  1094. }];
  1095. [self unlock];
  1096. if (valid == NO) {
  1097. return -1;
  1098. }
  1099. return bps / (float)count;
  1100. }
  1101. - (void)addTaskBPS:(float)bytesPerSecond endDate:(NSDate *)endDate
  1102. {
  1103. //if bytesPerSecond is less than or equal to zero, ignore.
  1104. if (bytesPerSecond <= 0) {
  1105. return;
  1106. }
  1107. [self lock];
  1108. if (self.taskQOS.count >= 5) {
  1109. [self.taskQOS removeObjectAtIndex:0];
  1110. }
  1111. PINTaskQOS *taskQOS = [[PINTaskQOS alloc] initWithBPS:bytesPerSecond endDate:endDate];
  1112. [self.taskQOS addObject:taskQOS];
  1113. [self.taskQOS sortUsingComparator:^NSComparisonResult(PINTaskQOS *obj1, PINTaskQOS *obj2) {
  1114. return [obj1.endDate compare:obj2.endDate];
  1115. }];
  1116. [self unlock];
  1117. }
  1118. #if DEBUG
  1119. - (void)setCurrentBytesPerSecond:(float)currentBPS
  1120. {
  1121. [self lockOnMainThread];
  1122. _overrideBPS = YES;
  1123. _currentBPS = currentBPS;
  1124. [self unlock];
  1125. }
  1126. #endif
  1127. - (NSUUID *)downloadImageWithURLs:(NSArray <NSURL *> *)urls
  1128. options:(PINRemoteImageManagerDownloadOptions)options
  1129. progressImage:(PINRemoteImageManagerImageCompletion)progressImage
  1130. completion:(PINRemoteImageManagerImageCompletion)completion
  1131. {
  1132. NSUUID *UUID = [NSUUID UUID];
  1133. if (urls.count <= 1) {
  1134. NSURL *url = [urls firstObject];
  1135. [self downloadImageWithURL:url
  1136. options:options
  1137. priority:PINRemoteImageManagerPriorityMedium
  1138. processorKey:nil
  1139. processor:nil
  1140. progressImage:progressImage
  1141. progressDownload:nil
  1142. completion:completion
  1143. inputUUID:UUID];
  1144. return UUID;
  1145. }
  1146. __weak typeof(self) weakSelf = self;
  1147. [self.concurrentOperationQueue pin_addOperationWithQueuePriority:PINRemoteImageManagerPriorityMedium block:^{
  1148. __block NSInteger highestQualityDownloadedIdx = -1;
  1149. typeof(self) strongSelf = weakSelf;
  1150. //check for the highest quality image already in cache. It's possible that an image is in the process of being
  1151. //cached when this is being run. In which case two things could happen:
  1152. // - If network conditions dictate that a lower quality image should be downloaded than the one that is currently
  1153. // being cached, it will be downloaded in addition. This is not ideal behavior, worst case scenario and unlikely.
  1154. // - If network conditions dictate that the same quality image should be downloaded as the one being cached, no
  1155. // new image will be downloaded as either the caching will have finished by the time we actually request it or
  1156. // the task will still exist and our callback will be attached. In this case, no detrimental behavior will have
  1157. // occurred.
  1158. [urls enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSURL *url, NSUInteger idx, BOOL *stop) {
  1159. typeof(self) strongSelf = weakSelf;
  1160. BlockAssert([url isKindOfClass:[NSURL class]], @"url must be of type URL");
  1161. NSString *cacheKey = [strongSelf cacheKeyForURL:url processorKey:nil];
  1162. //we don't actually need the object, just need to know it exists so that we can request it later
  1163. BOOL hasObject = [self.cache objectExistsForKey:cacheKey];
  1164. if (hasObject) {
  1165. highestQualityDownloadedIdx = idx;
  1166. *stop = YES;
  1167. }
  1168. }];
  1169. float currentBytesPerSecond = [strongSelf currentBytesPerSecond];
  1170. [strongSelf lock];
  1171. float highQualityQPSThreshold = [strongSelf highQualityBPSThreshold];
  1172. float lowQualityQPSThreshold = [strongSelf lowQualityBPSThreshold];
  1173. BOOL shouldUpgradeLowQualityImages = [strongSelf shouldUpgradeLowQualityImages];
  1174. [strongSelf unlock];
  1175. NSUInteger desiredImageURLIdx;
  1176. if (currentBytesPerSecond == -1 || currentBytesPerSecond >= highQualityQPSThreshold) {
  1177. desiredImageURLIdx = urls.count - 1;
  1178. } else if (currentBytesPerSecond <= lowQualityQPSThreshold) {
  1179. desiredImageURLIdx = 0;
  1180. } else if (urls.count == 2) {
  1181. desiredImageURLIdx = roundf((currentBytesPerSecond - lowQualityQPSThreshold) / ((highQualityQPSThreshold - lowQualityQPSThreshold) / (float)(urls.count - 1)));
  1182. } else {
  1183. desiredImageURLIdx = ceilf((currentBytesPerSecond - lowQualityQPSThreshold) / ((highQualityQPSThreshold - lowQualityQPSThreshold) / (float)(urls.count - 2)));
  1184. }
  1185. NSUInteger downloadIdx;
  1186. //if the highest quality already downloaded is less than what currentBPS would dictate and shouldUpgrade is
  1187. //set, download the new higher quality image. If no image has been cached, download the image dictated by
  1188. //current bps
  1189. if ((highestQualityDownloadedIdx < desiredImageURLIdx && shouldUpgradeLowQualityImages) || highestQualityDownloadedIdx == -1) {
  1190. downloadIdx = desiredImageURLIdx;
  1191. } else {
  1192. downloadIdx = highestQualityDownloadedIdx;
  1193. }
  1194. NSURL *downloadURL = [urls objectAtIndex:downloadIdx];
  1195. [strongSelf downloadImageWithURL:downloadURL
  1196. options:options
  1197. priority:PINRemoteImageManagerPriorityMedium
  1198. processorKey:nil
  1199. processor:nil
  1200. progressImage:progressImage
  1201. progressDownload:nil
  1202. completion:^(PINRemoteImageManagerResult *result) {
  1203. typeof(self) strongSelf = weakSelf;
  1204. //clean out any lower quality images from the cache
  1205. for (NSInteger idx = downloadIdx - 1; idx >= 0; idx--) {
  1206. [[strongSelf cache] removeObjectForKey:[strongSelf cacheKeyForURL:[urls objectAtIndex:idx] processorKey:nil]];
  1207. }
  1208. if (completion) {
  1209. completion(result);
  1210. }
  1211. }
  1212. inputUUID:UUID];
  1213. }];
  1214. return UUID;
  1215. }
  1216. #pragma mark - Caching
  1217. - (BOOL)materializeAndCacheObject:(id)object
  1218. key:(NSString *)key
  1219. options:(PINRemoteImageManagerDownloadOptions)options
  1220. outImage:(PINImage **)outImage
  1221. outAltRep:(id *)outAlternateRepresentation
  1222. {
  1223. return [self materializeAndCacheObject:object cacheInDisk:nil additionalCost:0 key:key options:options outImage:outImage outAltRep:outAlternateRepresentation];
  1224. }
  1225. //takes the object from the cache and returns an image or animated image.
  1226. //if it's a non-alternative representation and skipDecode is not set it also decompresses the image.
  1227. - (BOOL)materializeAndCacheObject:(id)object
  1228. cacheInDisk:(NSData *)diskData
  1229. additionalCost:(NSUInteger)additionalCost
  1230. key:(NSString *)key
  1231. options:(PINRemoteImageManagerDownloadOptions)options
  1232. outImage:(PINImage **)outImage
  1233. outAltRep:(id *)outAlternateRepresentation
  1234. {
  1235. NSAssert(object != nil, @"Object should not be nil.");
  1236. if (object == nil) {
  1237. return NO;
  1238. }
  1239. BOOL alternateRepresentationsAllowed = (PINRemoteImageManagerDisallowAlternateRepresentations & options) == 0;
  1240. BOOL skipDecode = (options & PINRemoteImageManagerDownloadOptionsSkipDecode) != 0;
  1241. __block id alternateRepresentation = nil;
  1242. __block PINImage *image = nil;
  1243. __block NSData *data = nil;
  1244. __block BOOL updateMemoryCache = NO;
  1245. PINRemoteImageMemoryContainer *container = nil;
  1246. if ([object isKindOfClass:[PINRemoteImageMemoryContainer class]]) {
  1247. container = (PINRemoteImageMemoryContainer *)object;
  1248. [container.lock lockWithBlock:^{
  1249. data = container.data;
  1250. }];
  1251. } else {
  1252. updateMemoryCache = YES;
  1253. // don't need to lock the container here because we just init it.
  1254. container = [[PINRemoteImageMemoryContainer alloc] init];
  1255. if ([object isKindOfClass:[PINImage class]]) {
  1256. data = diskData;
  1257. container.image = (PINImage *)object;
  1258. } else if ([object isKindOfClass:[NSData class]]) {
  1259. data = (NSData *)object;
  1260. } else {
  1261. //invalid item in cache
  1262. updateMemoryCache = NO;
  1263. data = nil;
  1264. container = nil;
  1265. }
  1266. container.data = data;
  1267. }
  1268. if (alternateRepresentationsAllowed) {
  1269. alternateRepresentation = [_alternateRepProvider alternateRepresentationWithData:data options:options];
  1270. }
  1271. if (alternateRepresentation == nil) {
  1272. //we need the image
  1273. [container.lock lockWithBlock:^{
  1274. image = container.image;
  1275. }];
  1276. if (image == nil) {
  1277. image = [PINImage pin_decodedImageWithData:container.data skipDecodeIfPossible:skipDecode];
  1278. if (skipDecode == NO) {
  1279. [container.lock lockWithBlock:^{
  1280. updateMemoryCache = YES;
  1281. container.image = image;
  1282. }];
  1283. }
  1284. }
  1285. }
  1286. if (updateMemoryCache) {
  1287. [container.lock lockWithBlock:^{
  1288. NSUInteger cacheCost = additionalCost;
  1289. cacheCost += [container.data length];
  1290. CGImageRef imageRef = container.image.CGImage;
  1291. NSAssert(container.image == nil || imageRef != NULL, @"We only cache a decompressed image if we decompressed it ourselves. In that case, it should be backed by a CGImageRef.");
  1292. if (imageRef) {
  1293. cacheCost += CGImageGetHeight(imageRef) * CGImageGetBytesPerRow(imageRef);
  1294. }
  1295. [self.cache setObjectInMemory:container forKey:key withCost:cacheCost];
  1296. }];
  1297. }
  1298. if (diskData) {
  1299. [self.cache setObjectOnDisk:diskData forKey:key];
  1300. }
  1301. if (outImage) {
  1302. *outImage = image;
  1303. }
  1304. if (outAlternateRepresentation) {
  1305. *outAlternateRepresentation = alternateRepresentation;
  1306. }
  1307. if (image == nil && alternateRepresentation == nil) {
  1308. PINLog(@"Invalid item in cache");
  1309. [self.cache removeObjectForKey:key completion:nil];
  1310. return NO;
  1311. }
  1312. return YES;
  1313. }
  1314. - (NSString *)cacheKeyForURL:(NSURL *)url processorKey:(NSString *)processorKey
  1315. {
  1316. NSString *cacheKey = [url absoluteString];
  1317. if (processorKey.length > 0) {
  1318. cacheKey = [cacheKey stringByAppendingString:[NSString stringWithFormat:@"-<%@>", processorKey]];
  1319. }
  1320. //PINDiskCache uses this key as the filename of the file written to disk
  1321. //Due to the current filesystem used in Darwin, this name must be limited to 255 chars.
  1322. //In case the generated key exceeds PINRemoteImageManagerCacheKeyMaxLength characters,
  1323. //we return the hash of it instead.
  1324. if (cacheKey.length > PINRemoteImageManagerCacheKeyMaxLength) {
  1325. __block CC_MD5_CTX ctx;
  1326. CC_MD5_Init(&ctx);
  1327. NSData *data = [cacheKey dataUsingEncoding:NSUTF8StringEncoding];
  1328. [data enumerateByteRangesUsingBlock:^(const void * _Nonnull bytes, NSRange byteRange, BOOL * _Nonnull stop) {
  1329. CC_MD5_Update(&ctx, bytes, (CC_LONG)byteRange.length);
  1330. }];
  1331. unsigned char digest[CC_MD5_DIGEST_LENGTH];
  1332. CC_MD5_Final(digest, &ctx);
  1333. NSMutableString *hexString = [NSMutableString stringWithCapacity:(CC_MD5_DIGEST_LENGTH * 2)];
  1334. for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
  1335. [hexString appendFormat:@"%02lx", (unsigned long)digest[i]];
  1336. }
  1337. cacheKey = [hexString copy];
  1338. }
  1339. return cacheKey;
  1340. }
  1341. - (void)objectForKey:(NSString *)key options:(PINRemoteImageManagerDownloadOptions)options completion:(void (^)(BOOL found, BOOL valid, PINImage *image, id alternativeRepresentation))completion
  1342. {
  1343. if ((options & PINRemoteImageManagerDownloadOptionsIgnoreCache) != 0) {
  1344. completion(NO, YES, nil, nil);
  1345. return;
  1346. }
  1347. void (^materialize)(id object) = ^(id object) {
  1348. PINImage *image = nil;
  1349. id alternativeRepresentation = nil;
  1350. BOOL valid = [self materializeAndCacheObject:object
  1351. key:key
  1352. options:options
  1353. outImage:&image
  1354. outAltRep:&alternativeRepresentation];
  1355. completion(YES, valid, image, alternativeRepresentation);
  1356. };
  1357. PINRemoteImageMemoryContainer *container = [self.cache objectFromMemoryForKey:key];
  1358. if (container) {
  1359. materialize(container);
  1360. } else {
  1361. [self.cache objectFromDiskForKey:key completion:^(id<PINRemoteImageCaching> _Nonnull cache,
  1362. NSString *_Nonnull key,
  1363. id _Nullable object) {
  1364. if (object) {
  1365. materialize(object);
  1366. } else {
  1367. completion(NO, YES, nil, nil);
  1368. }
  1369. }];
  1370. }
  1371. }
  1372. @end
  1373. @implementation NSOperationQueue (PINRemoteImageManager)
  1374. - (void)pin_addOperationWithQueuePriority:(PINRemoteImageManagerPriority)priority block:(void (^)(void))block
  1375. {
  1376. NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:block];
  1377. operation.queuePriority = operationPriorityWithImageManagerPriority(priority);
  1378. if ([PINRemoteImageManager supportsQOS] == NO) {
  1379. #pragma clang diagnostic push
  1380. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1381. operation.threadPriority = 0.2;
  1382. #pragma clang diagnostic pop
  1383. }
  1384. [self addOperation:operation];
  1385. }
  1386. @end
  1387. @implementation PINTaskQOS
  1388. - (instancetype)initWithBPS:(float)bytesPerSecond endDate:(NSDate *)endDate
  1389. {
  1390. if (self = [super init]) {
  1391. self.endDate = endDate;
  1392. self.bytesPerSecond = bytesPerSecond;
  1393. }
  1394. return self;
  1395. }
  1396. @end