SDWebImage源码解析(四)

Posted by 黄成都 on 2017-05-04
Words 4.6k and Reading Time 22 Minutes
Viewed Times

1 概述

这篇博文将分析SDWebImageDownloaderSDWebImageDownloaderOperationSDWebImage通过这两个类处理图片的网络加载。SDWebImageManager通过属性imageDownloader持有SDWebImageDownloader并且调用它的downloadImageWithURL来从网络加载图片。SDWebImageDownloader实现了图片加载的具体处理,如果图片在缓存存在则从缓存区,如果缓存不存在,则直接创建一个SDWebImageDownloaderOperation对象来下载图片。管理NSURLRequest对象请求头的封装、缓存、cookie的设置。加载选项的处理等功能。管理Operation之间的依赖关系。SDWebImageDownloaderOperation是一个自定义的并行Operation子类。这个类主要实现了图片下载的具体操作、以及图片下载完成以后的图片解压缩、Operation生命周期管理等。

2 SDWebImageDownloader分析

SDWebImageDownlaoder是一个单列对象,主要做了如下工作:

  • 定义了SDWebImageDownloaderOptions这个枚举属性,通过这个枚举属性来设置图片从网络加载的不同情况。
  • 定义并管理了NSURLSession对象,通过这个对象来做网络请求,并且实现对象的代理方法。
  • 定义一个NSURLRequest对象,并且管理请求头的拼装。
  • 对于每一个网络请求,通过一个SDWebImageDownloaderOperation自定义的NSOperation来操作网络下载。
  • 管理网络加载过程和完成时候的回调工作。通过addProgressCallback实现。

2.1 SDWebImageDownloaderOptions枚举类型

可以通过这个枚举类型来控制网络加载、请求头、缓存策略等。

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
typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
SDWebImageDownloaderLowPriority = 1 << 0,
SDWebImageDownloaderProgressiveDownload = 1 << 1,
/*
*默认情况下,http请求阻止使用NSURLCache对象。如果设置了这个标记,则NSURLCache会被http请求使用。
*/
SDWebImageDownloaderUseNSURLCache = 1 << 2,
/*
*如果image/imageData是从NSURLCache返回的。则completion这个回调会返回nil。
*/
SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
/*
*如果app进入后台模式,是否继续下载。这个是通过在后台申请时间来完成这个操作。如果指定的时间范围内没有完成,则直接取消下载。
*/
SDWebImageDownloaderContinueInBackground = 1 << 4,
/*
处理缓存在`NSHTTPCookieStore`对象里面的cookie。通过设置`NSMutableURLRequest.HTTPShouldHandleCookies = YES`来实现的。
*/
SDWebImageDownloaderHandleCookies = 1 << 5,
/*
*允许非信任的SSL证书请求。
*在测试的时候很有用。但是正式环境要小心使用。
*/
SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
/*
* 默认情况下,图片加载的顺序是根据加入队列的顺序加载的。但是这个标记会把任务加入队列的最前面。
*/
SDWebImageDownloaderHighPriority = 1 << 7,
/*
*默认情况下,图片会按照他的原始大小来解码显示。这个属性会调整图片的尺寸到合适的大小根据设备的内存限制。
*如果`SDWebImageProgressiveDownload`标记被设置了,则这个flag不起作用。
*/
SDWebImageDownloaderScaleDownLargeImages = 1 << 8,
};

2.2 SDWebImageDownloader的属性和初始化

可以通过它的属性对最大并行下载数量、超时时间、operation之间的下载顺序、做处理。

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
/**
* 当图片下载完成以后,加压缩图片以后再换成。这样可以提升性能但是会占用更多的存储空间。
* 模式YES,如果你因为过多的内存消耗导致一个奔溃,可以把这个属性设置为NO。
*/
@property (assign, nonatomic) BOOL shouldDecompressImages;

/**
最大并行下载的数量
*/
@property (assign, nonatomic) NSInteger maxConcurrentDownloads;

/**
当前并行下载数量
*/
@property (readonly, nonatomic) NSUInteger currentDownloadCount;
/**
下载超时时间设置
*/
@property (assign, nonatomic) NSTimeInterval downloadTimeout;
/**
改变下载operation的执行顺序。默认是FIFO。
*/
@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;

/**
单列方法。返回一个单列对象
@return 返回一个单列的SDWebImageDownloader对象
*/
+ (nonnull instancetype)sharedDownloader;
/**
为图片加载request设置一个SSL证书对象。
*/
@property (strong, nonatomic, nullable) NSURLCredential *urlCredential;

/**
Basic认证请求设置用户名和密码
*/
@property (strong, nonatomic, nullable) NSString *username;
@property (strong, nonatomic, nullable) NSString *password;

/**
* 为http请求设置header。
* 每一request执行的时候,这个Block都会被执行。用于向http请求添加请求域。
*/
@property (nonatomic, copy, nullable) SDWebImageDownloaderHeadersFilterBlock headersFilter;
/**
初始化一个请求对象

@param sessionConfiguration NSURLSessionTask初始化配置
@return 返回一个SDWebImageDownloader对象
*/
- (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
/**
设置请求头域

@param value 请求头域值
@param field 请求头域名
*/
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field;
/*
*获取请求头域的值
*/
- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field;
/**
设置一个`SDWebImageDownloaderOperation`的子类作为`NSOperation`来构建request来下载一张图片。

@param operationClass 指定的子类
*/
- (void)setOperationClass:(nullable Class)operationClass;
/**
所有的下载图片的Operation都加入NSoperationQueue中
*/
@property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue;

/**
最后一个添加的Operation
*/
@property (weak, nonatomic, nullable) NSOperation *lastAddedOperation;

/**
自定义的NSOperation子类
*/
@property (assign, nonatomic, nullable) Class operationClass;

/**
用于记录url和他对应的SDWebImageDownloaderOperation对象。
*/
@property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, SDWebImageDownloaderOperation *> *URLOperations;

/**
请求头域字典
*/
@property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *HTTPHeaders;
/**
通过这个`NSURLSession`创建请求
*/
@property (strong, nonatomic) NSURLSession *session;

2.2 downloadImageWithURL方法

这个方法是SDWebImageDownloader的核心方法。SDWebImageManager通过这个方法来实现图片从网络加载。

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
/**
新建一个SDWebImageDownloadOperation对象来来做具体的下载操作。同时指定缓存策略、cookie策略、自定义请求头域等。

@param url url
@param options 加载选项
@param progressBlock 进度progress
@param completedBlock 完成回调
@return 返回一个SDWebImageDownloadToken,用于关联一个请求
*/
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
__weak SDWebImageDownloader *wself = self;

return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{
__strong __typeof (wself) sself = wself;
NSTimeInterval timeoutInterval = sself.downloadTimeout;
if (timeoutInterval == 0.0) {
timeoutInterval = 15.0;
}
/*
*为了避免可能存在的NSURLCache和SDImageCache同时缓存。我们默认不允许image对象的NSURLCache对象。
具体缓存策略参考http://www.jianshu.com/p/855c2c6e761f
*/
NSURLRequestCachePolicy cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
if (options & SDWebImageDownloaderUseNSURLCache) {
if (options & SDWebImageDownloaderIgnoreCachedResponse) {
cachePolicy = NSURLRequestReturnCacheDataDontLoad;
} else {
cachePolicy = NSURLRequestUseProtocolCachePolicy;
}
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
//使用cookies
request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
//使用管道
request.HTTPShouldUsePipelining = YES;
//添加自定义请求头
if (sself.headersFilter) {
request.allHTTPHeaderFields = sself.headersFilter(url, [sself.HTTPHeaders copy]);
}
else {
request.allHTTPHeaderFields = sself.HTTPHeaders;
}
//初始化一个自定义NSOperation对象
SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options];
//是否解压缩返回的图片
operation.shouldDecompressImages = sself.shouldDecompressImages;
//指定验证信息
if (sself.urlCredential) {
//SSL验证
operation.credential = sself.urlCredential;
} else if (sself.username && sself.password) {
//Basic验证
operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession];
}
//指定优先级
if (options & SDWebImageDownloaderHighPriority) {
operation.queuePriority = NSOperationQueuePriorityHigh;
} else if (options & SDWebImageDownloaderLowPriority) {
operation.queuePriority = NSOperationQueuePriorityLow;
}
//把operatin添加进入NSOperationQueue中
[sself.downloadQueue addOperation:operation];
/*
如果是LIFO这种模式,则需要手动指定operation之间的依赖关系
*/
if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
//如果是LIFO,则让前面的operation依赖于最新添加的operation
[sself.lastAddedOperation addDependency:operation];
sself.lastAddedOperation = operation;
}
return operation;
}];
}
/**
给下载过程添加进度

@param progressBlock 进度Block
@param completedBlock 完成Block
@param url url地址
@param createCallback nil
@return 返回SDWebImageDownloadToken。方便后面取消
*/
- (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock
completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock
forURL:(nullable NSURL *)url
createCallback:(SDWebImageDownloaderOperation *(^)())createCallback {
// The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
if (url == nil) {
if (completedBlock != nil) {
completedBlock(nil, nil, nil, NO);
}
return nil;
}

__block SDWebImageDownloadToken *token = nil;

dispatch_barrier_sync(self.barrierQueue, ^{
//看是否当前url是否有对应的Operation图片加载对象
SDWebImageDownloaderOperation *operation = self.URLOperations[url];
//如果没有,则直接创建一个。
if (!operation) {
//创建一个operation。并且添加到URLOperation中。
operation = createCallback();
self.URLOperations[url] = operation;

__weak SDWebImageDownloaderOperation *woperation = operation;
//设置operation操作完成以后的回调
operation.completionBlock = ^{
SDWebImageDownloaderOperation *soperation = woperation;
if (!soperation) return;
if (self.URLOperations[url] == soperation) {
[self.URLOperations removeObjectForKey:url];
};
};
}
id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];
token = [SDWebImageDownloadToken new];
token.url = url;
token.downloadOperationCancelToken = downloadOperationCancelToken;
});

return token;
}

如果要取消一个下载操作,使用cancel方法来处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
移除一个图片加载操作

@param token 通过token来确定操作
*/
- (void)cancel:(nullable SDWebImageDownloadToken *)token {
dispatch_barrier_async(self.barrierQueue, ^{
SDWebImageDownloaderOperation *operation = self.URLOperations[token.url];
BOOL canceled = [operation cancel:token.downloadOperationCancelToken];
if (canceled) {
[self.URLOperations removeObjectForKey:token.url];
}
});
}

另外还有NSURLSession的代理方法,这里就不细讲了。如果兴趣可以参考AFNetWorking源码分析。

3 SDWebImageDownloaderOperation分析

SDWebImageDownloaderOperation是一个自定义、并行的NSOperation子类。这个子类主要实现的功能有:

  • 由于只自定义的并行NSOperation,所以需要管理executing,finished等各种属性的处理,并且手动触发KVO。
  • start(NSOperation规定,没有为什么)方法里面实现主要逻辑。
  • NSURLSessionTaskDelegateNSURLSessionDataDelegate中处理数据的加载,以及进度Block的处理。
  • 如果unownedSession属性因为某种原因是nil,则手动初始化一个做网络请求。
  • 在代理方法中对认证、数据拼装、完成回调Block做处理。
  • 通过发送SDWebImageDownloadStopNotification,SDWebImageDownloadFinishNotification,SDWebImageDownloadReceiveResponseNotification,SDWebImageDownloadStartNotification来通知Operation的状态。

具体完整源码如下:

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
NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification";
NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification";

static NSString *const kProgressCallbackKey = @"progress";
static NSString *const kCompletedCallbackKey = @"completed";

typedef NSMutableDictionary<NSString *, id> SDCallbacksDictionary;

@interface SDWebImageDownloaderOperation ()

/**
回调Block列表
*/
@property (strong, nonatomic, nonnull) NSMutableArray<SDCallbacksDictionary *> *callbackBlocks;

/**
自定义并行Operation需要管理的两个属性。默认是readonly的,我们这里通过声明改为可修改的。方便我们在后面操作。
*/
@property (assign, nonatomic, getter = isExecuting) BOOL executing;
@property (assign, nonatomic, getter = isFinished) BOOL finished;

/**
存储图片数据
*/
@property (strong, nonatomic, nullable) NSMutableData *imageData;
/**
通过SDWebImageDownloader传过来。所以这里是weak。因为他是通过SDWebImageDownloader管理的。
*/
@property (weak, nonatomic, nullable) NSURLSession *unownedSession;
/**
如果unownedSession是nil,我们需要手动创建一个并且管理他的生命周期和代理方法
*/
@property (strong, nonatomic, nullable) NSURLSession *ownedSession;

/**
dataTask对象
*/
@property (strong, nonatomic, readwrite, nullable) NSURLSessionTask *dataTask;

/**
一个并行queue。用于控制数据的处理
*/
@property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t barrierQueue;

#if SD_UIKIT

/**
如果用户设置了后台继续加载选线。则通过backgroundTask来继续下载图片
*/
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
#endif

@end

@implementation SDWebImageDownloaderOperation {
size_t width, height;
#if SD_UIKIT || SD_WATCH
UIImageOrientation orientation;
#endif
}

@synthesize executing = _executing;
@synthesize finished = _finished;

- (nonnull instancetype)init {
return [self initWithRequest:nil inSession:nil options:0];
}

- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
inSession:(nullable NSURLSession *)session
options:(SDWebImageDownloaderOptions)options {
if ((self = [super init])) {
_request = [request copy];
_shouldDecompressImages = YES;
_options = options;
_callbackBlocks = [NSMutableArray new];
//默认情况下。_executing和finished都是NO
_executing = NO;
_finished = NO;
_expectedSize = 0;
_unownedSession = session;
_barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderOperationBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
}
return self;
}

- (void)dealloc {
SDDispatchQueueRelease(_barrierQueue);
}

/**
给Operation添加进度和回调Block

@param progressBlock 进度Block
@param completedBlock 回调Block
@return 回调字典
*/
- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
SDCallbacksDictionary *callbacks = [NSMutableDictionary new];
//把Operation对应的回调和进度Block存入一个字典中
if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
//把完成和进度Block加入callbackBlocks中
dispatch_barrier_async(self.barrierQueue, ^{
[self.callbackBlocks addObject:callbacks];
});
return callbacks;
}

- (nullable NSArray<id> *)callbacksForKey:(NSString *)key {
__block NSMutableArray<id> *callbacks = nil;
dispatch_sync(self.barrierQueue, ^{
// We need to remove [NSNull null] because there might not always be a progress block for each callback
callbacks = [[self.callbackBlocks valueForKey:key] mutableCopy];
[callbacks removeObjectIdenticalTo:[NSNull null]];
});
return [callbacks copy]; // strip mutability here
}

- (BOOL)cancel:(nullable id)token {
__block BOOL shouldCancel = NO;
dispatch_barrier_sync(self.barrierQueue, ^{
[self.callbackBlocks removeObjectIdenticalTo:token];
if (self.callbackBlocks.count == 0) {
shouldCancel = YES;
}
});
if (shouldCancel) {
[self cancel];
}
return shouldCancel;
}

/**
并行的Operation需要重写这个方法.在这个方法里面做具体的处理
*/
- (void)start {
@synchronized (self) {
if (self.isCancelled) {
self.finished = YES;
[self reset];
return;
}

#if SD_UIKIT
Class UIApplicationClass = NSClassFromString(@"UIApplication");
BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)];
//如果用户甚至了Background模式,则设置一个backgroundTask
if (hasApplication && [self shouldContinueWhenAppEntersBackground]) {
__weak __typeof__ (self) wself = self;
UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)];
self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
//background结束以后。做清理工作
__strong __typeof (wself) sself = wself;
if (sself) {
[sself cancel];
[app endBackgroundTask:sself.backgroundTaskId];
sself.backgroundTaskId = UIBackgroundTaskInvalid;
}
}];
}
#endif
NSURLSession *session = self.unownedSession;
//如果SDWebImageDownloader传入的session是nil,则自己手动初始化一个。
if (!self.unownedSession) {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 15;

/**
* Create the session for this task
* We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate
* method calls and completion handler calls.
*/
self.ownedSession = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:nil];
session = self.ownedSession;
}

self.dataTask = [session dataTaskWithRequest:self.request];
self.executing = YES;
}
//发送请求
[self.dataTask resume];

if (self.dataTask) {
//第一次调用进度BLOCK
for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) {
progressBlock(0, NSURLResponseUnknownLength, self.request.URL);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self];
});
} else {
[self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}]];
}

#if SD_UIKIT
Class UIApplicationClass = NSClassFromString(@"UIApplication");
if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
return;
}
if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)];
[app endBackgroundTask:self.backgroundTaskId];
self.backgroundTaskId = UIBackgroundTaskInvalid;
}
#endif
}

/**
如果要取消一个Operation,就会调用这个方法。
*/
- (void)cancel {
@synchronized (self) {
[self cancelInternal];
}
}

- (void)cancelInternal {
if (self.isFinished) return;
[super cancel];

if (self.dataTask) {
[self.dataTask cancel];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
});

// As we cancelled the connection, its callback won't be called and thus won't
// maintain the isFinished and isExecuting flags.
//更新状态
if (self.isExecuting) self.executing = NO;
if (!self.isFinished) self.finished = YES;
}

[self reset];
}

- (void)done {
self.finished = YES;
self.executing = NO;
[self reset];
}

- (void)reset {
dispatch_barrier_async(self.barrierQueue, ^{
[self.callbackBlocks removeAllObjects];
});
self.dataTask = nil;
self.imageData = nil;
if (self.ownedSession) {
[self.ownedSession invalidateAndCancel];
self.ownedSession = nil;
}
}

/**
需要手动触发_finished的KVO。这个是自定义并发`NSOperation`必须实现的。

@param finished 改变状态
*/
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
/**
需要手动触发_executing的KVO。这个是自定义并发`NSOperation`必须实现的。

@param executing 改变状态
*/
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}

/**
返回YES,表明这个NSOperation对象是并发的

@return 返回bool值
*/
- (BOOL)isConcurrent {
return YES;
}

#pragma mark NSURLSessionDataDelegate

/*

*/
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {

//'304 Not Modified' is an exceptional one
if (![response respondsToSelector:@selector(statusCode)] || (((NSHTTPURLResponse *)response).statusCode < 400 && ((NSHTTPURLResponse *)response).statusCode != 304)) {
//期望的总长度
NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
self.expectedSize = expected;
//进度回调Block
for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) {
progressBlock(0, expected, self.request.URL);
}

self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
self.response = response;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:self];
});
}
else {
NSUInteger code = ((NSHTTPURLResponse *)response).statusCode;

//This is the case when server returns '304 Not Modified'. It means that remote image is not changed.
//In case of 304 we need just cancel the operation and return cached image from the cache.
/*
如果返回304表示图片么有变化。在这种情况下,我们只需要取消operation并且返回缓存的图片就可以了。
*/
if (code == 304) {
[self cancelInternal];
} else {
[self.dataTask cancel];
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
});

[self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:((NSHTTPURLResponse *)response).statusCode userInfo:nil]];

[self done];
}
//这个表示允许继续加载
if (completionHandler) {
completionHandler(NSURLSessionResponseAllow);
}
}
/*
*会被多次调用。获取图片数据
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {

[self.imageData appendData:data];

if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0) {
// The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
// Thanks to the author @Nyx0uf

// Get the total bytes downloaded
//获取已经下载的数据长度
const NSInteger totalSize = self.imageData.length;

// Update the data source, we must pass ALL the data, not just the new bytes
CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL);
/*
*width和height都是0的话表示还么有获取到图片的高度和宽度。我们可以通过数据来获取图片的宽度和高度
*此时表示第一次收到图片数据
*/
if (width + height == 0) {
//获取图片数据的属性
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
if (properties) {
NSInteger orientationValue = -1;
//获取高度值
CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
if (val) CFNumberGetValue(val, kCFNumberLongType, &height);
//获取宽度值
val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
if (val) CFNumberGetValue(val, kCFNumberLongType, &width);
//获取图片的方向值
val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
CFRelease(properties);

// When we draw to Core Graphics, we lose orientation information,
// which means the image below born of initWithCGIImage will be
// oriented incorrectly sometimes. (Unlike the image born of initWithData
// in didCompleteWithError.) So save it here and pass it on later.
#if SD_UIKIT || SD_WATCH
orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)];
#endif
}
}
/*
* 这个表示已经收到部分图片数据并且还么有获取到所有的图片数据
*/
if (width + height > 0 && totalSize < self.expectedSize) {
// Create the image
CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);

#if SD_UIKIT || SD_WATCH
// Workaround for iOS anamorphic image
if (partialImageRef) {
const size_t partialHeight = CGImageGetHeight(partialImageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if (bmContext) {
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef);
CGImageRelease(partialImageRef);
partialImageRef = CGBitmapContextCreateImage(bmContext);
CGContextRelease(bmContext);
}
else {
CGImageRelease(partialImageRef);
partialImageRef = nil;
}
}
#endif

if (partialImageRef) {
#if SD_UIKIT || SD_WATCH
UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation];
#elif SD_MAC
UIImage *image = [[UIImage alloc] initWithCGImage:partialImageRef size:NSZeroSize];
#endif
//获取图片url对应的key
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
//根据原始图片数据获取对应scale下面的图片
UIImage *scaledImage = [self scaledImageForKey:key image:image];
//是否解压缩图片
if (self.shouldDecompressImages) {
/*
*解压缩图片
*/
image = [UIImage decodedImageWithImage:scaledImage];
}
else {
image = scaledImage;
}
CGImageRelease(partialImageRef);

[self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO];
}
}

CFRelease(imageSource);
}

for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) {
progressBlock(self.imageData.length, self.expectedSize, self.request.URL);
}
}

- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
willCacheResponse:(NSCachedURLResponse *)proposedResponse
completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler {
//根据request的选项。决定是否缓存NSCachedURLResponse
NSCachedURLResponse *cachedResponse = proposedResponse;

if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
// Prevents caching of responses
cachedResponse = nil;
}
if (completionHandler) {
completionHandler(cachedResponse);
}
}

#pragma mark NSURLSessionTaskDelegate
/*
网络请求加载完成,在这里处理获得的数据
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
@synchronized(self) {
self.dataTask = nil;
//发送图片下载完成的通知
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
if (!error) {
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:self];
}
});
}
if (error) {
[self callCompletionBlocksWithError:error];
} else {
if ([self callbacksForKey:kCompletedCallbackKey].count > 0) {
if (self.imageData) {
UIImage *image = [UIImage sd_imageWithData:self.imageData];
//获取url对应的缓存Key
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];

image = [self scaledImageForKey:key image:image];

// Do not force decoding animated GIFs
if (!image.images) {
//是否加压缩图片数据
if (self.shouldDecompressImages) {
//如果设置了SDWebImageDownloaderScaleDownLargeImages。则返回处理过的图片
if (self.options & SDWebImageDownloaderScaleDownLargeImages) {
#if SD_UIKIT || SD_WATCH
image = [UIImage decodedAndScaledDownImageWithImage:image];
[self.imageData setData:UIImagePNGRepresentation(image)];
#endif
} else {
image = [UIImage decodedImageWithImage:image];
}
}
}
//构建回调Block
if (CGSizeEqualToSize(image.size, CGSizeZero)) {
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}]];
} else {
[self callCompletionBlocksWithImage:image imageData:self.imageData error:nil finished:YES];
}
} else {
[self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}]];
}
}
}
[self done];
}

/*
验证HTTPS的证书
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {

NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
//使用可信任证书机构的证书
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//如果SDWebImageDownloaderAllowInvalidSSLCertificates属性设置了,则不验证SSL证书。直接信任
if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates)) {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
} else {
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
disposition = NSURLSessionAuthChallengeUseCredential;
}
} else {
//使用自己生成的证书
if (challenge.previousFailureCount == 0) {
if (self.credential) {
credential = self.credential;
disposition = NSURLSessionAuthChallengeUseCredential;
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
}
//验证证书
if (completionHandler) {
completionHandler(disposition, credential);
}
}
#pragma mark Helper methods

#if SD_UIKIT || SD_WATCH

/**
把整数转换为对应的枚举值

@param value 整数值
@return 枚举值
*/
+ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value {
switch (value) {
case 1:
return UIImageOrientationUp;
case 3:
return UIImageOrientationDown;
case 8:
return UIImageOrientationLeft;
case 6:
return UIImageOrientationRight;
case 2:
return UIImageOrientationUpMirrored;
case 4:
return UIImageOrientationDownMirrored;
case 5:
return UIImageOrientationLeftMirrored;
case 7:
return UIImageOrientationRightMirrored;
default:
return UIImageOrientationUp;
}
}
#endif

/**
* 通过image对象获取对应scale模式下的图像
*/
- (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
return SDScaledImageForKey(key, image);
}

- (BOOL)shouldContinueWhenAppEntersBackground {
return self.options & SDWebImageDownloaderContinueInBackground;
}

- (void)callCompletionBlocksWithError:(nullable NSError *)error {
[self callCompletionBlocksWithImage:nil imageData:nil error:error finished:YES];
}
/**
处理回调

@param image UIImage数据
@param imageData Image的data数据
@param error 错误
@param finished 是否完成的标记位
*/
- (void)callCompletionBlocksWithImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
error:(nullable NSError *)error
finished:(BOOL)finished {
//获取key对应的回调Block数组
NSArray<id> *completionBlocks = [self callbacksForKey:kCompletedCallbackKey];
dispatch_main_async_safe(^{
//调用回调
for (SDWebImageDownloaderCompletedBlock completedBlock in completionBlocks) {
completedBlock(image, imageData, error, finished);
}
});
}
@end

最后原文地址.html),demo地址


...

...

00:00
00:00