简书简述

AFN中的<UIImageView+AFNetworking>的解读


距离上一篇文章到这篇文章,已经有一段时间了。随着时间推移,人也变得越来越懒,以前回家还能抽出半小时看看博客,学习一下知识,填补一下半路出家的我。随着公司项目的停滞,自己也开始停滞不前,不想看代码,也不想看博客,也不想运动,就喜欢宅。睁眼上班-->上班就水群,到下班-->下班回家-->回家看娱乐节目-->12点睡觉-->睁眼上班如此重复5天,再睁眼看表-->还可以睡-->接着睡-->睁眼看表-->吃饭-->睡觉-->睁眼看表再次循环2天,在循环5天………

AFN中的&lt;UIImageView+AFNetworking&gt;的解读

生活要激情

代码虐我千百遍,我待Bug如初恋

《AFN》源码解读,从创建项目开始读,但现在已经两个多月了,刚开始看,看了半天,就看懂三个字符AFN——妈的,哥不读了,搁置一个月,生活继续流浪,代码还是读吧,慢慢开始读下去了,又认识三个单词session、Tast、DataTast、UploadTask、DownloadTask妈的,哥不懂了,都是什么和什么啊,代码虐我千百遍,我待代码如初恋,又开始读起来了……….断断续续读了两个多月,大概意思基本看懂,再次总结下<UIImageView+AFNetworking>的使用,后期会给出SDWebImage的解读和比较

<UIImageView+AFNetworking>

  • 先看一下<UIImageView+AFNetworking>业务逻辑

    AFN中的&lt;UIImageView+AFNetworking&gt;的解读

    业务逻辑

  • 先看一下<UIImageView+AFNetworking>里面类之间的关联

AFN中的&lt;UIImageView+AFNetworking&gt;的解读

image.png

下面看一下主要代码的解读

  /*** 直接设置图片的url*/   - (void)setImageWithURL:(NSURL *)url;    /*** 由占位图片的方法*/   - (void)setImageWithURL:(NSURL *)url    placeholderImage:(nullable UIImage *)placeholderImage;    /*** 由占位图片的方法并且由成功和失败的返回值,并且逻辑都是在此方法里面*/   - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest           placeholderImage:(nullable UIImage *)placeholderImage                    success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success                    failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;   /*** 取消当前的下载的图片*/     - (void)cancelImageDownloadTask; 

详细解读

  /**  加载带有占位图片的url图片   @param url              图片的url    @param placeholderImage 占位图  */ - (void)setImageWithURL:(NSURL *)url    placeholderImage:(UIImage *)placeholderImage {        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];       /**添加请求头为图片请求*/       [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];         /**注意我们可以在这里设置request的请求的缓存策略,来实现图片的加载情况*/       [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; } 

/** 判断请求里面的缓存策略
1.NSURLRequestUseProtocolCachePolicy 默认的cache policy,使用Protocol协议定义。
2.NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载。
3.NSURLRequestReturnCacheDataDontLoad 只使用cache数据,如果不存在cache,请求失败;用于没有建立网络连接离线模式
4.NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载。
5.NSURLRequestReloadIgnoringLocalAndRemoteCacheData 忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似。
6.NSURLRequestReloadRevalidatingCacheData :验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据
*/

AFN中图片的加载步骤

 - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest           placeholderImage:(UIImage *)placeholderImage                    success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success                    failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { /**请求的url为空*/ if ([urlRequest URL] == nil) {     /**取消下载*/     [self cancelImageDownloadTask];     self.image = placeholderImage;     return; } /**AFImageDownloadReceipt 图片下载对象,判断当前图片下载数据对象是否是当前的图片的,如果一直表示图片正在下载中*/ if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){     return; } /**取消之前下载*/ [self cancelImageDownloadTask]; /**设置一个图片对应的一个AFImageDownloader*/ AFImageDownloader *downloader = [[self class] sharedImageDownloader]; id <AFImageRequestCache> imageCache = downloader.imageCache;  //Use the image from the image cache if it exists /**根据图片的request和标志符去内存查询*/ UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; if (cachedImage) {/// 内存中由图片     if (success) {         success(urlRequest, nil, cachedImage);     } else {         self.image = cachedImage;     }     /**将下载的管理器设置为nil*/     [self clearActiveDownloadInformation]; } else {/// 内存中没有找到图片     if (placeholderImage) {         self.image = placeholderImage;     }      __weak __typeof(self)weakSelf = self;     NSUUID *downloadID = [NSUUID UUID];     AFImageDownloadReceipt *receipt;     receipt = [downloader                downloadImageForURLRequest:urlRequest                withReceiptID:downloadID                success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {                    __strong __typeof(weakSelf)strongSelf = weakSelf;                     /**判断任务的UDID是否和当前的UDID一致*/                    if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {                        if (success) {/// 如果设置了成功block,则回掉成功block                            success(request, response, responseObject);                        } else if(responseObject) {/// 判断回掉的图片是否有值,有值直接设置图片                            strongSelf.image = responseObject;                        }                         /**将当前图片请求的任务对象设置为nil*/                        [strongSelf clearActiveDownloadInformation];                    }                 }                failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {/// 失败回掉                    __strong __typeof(weakSelf)strongSelf = weakSelf;                     if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {                         if (failure) {                             failure(request, response, error);                         }                         [strongSelf clearActiveDownloadInformation];                     }                }];     /**将下载任务对象设置给当前UIImageView*/     self.af_activeImageDownloadReceipt = receipt; } } 
  • 判断当前图片是否在下载中

     /**    判断任务请求是否和请求的url是否一直   @param urlRequest url请求  */ - (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {   /**根据请求的url来判断*/ return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; } 
  • 重新设置图片的url,取消之前未下载完毕的任务

     - (void)cancelImageDownloadTask {     /**每一个UIImagView都有一个活跃的下载图片数据对象,当对象不能为空的时候,取消之前的下载*/     if (self.af_activeImageDownloadReceipt != nil)  {       [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];   [self clearActiveDownloadInformation];      }   } 

AFImageDownloader下载数据

- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request                                               withReceiptID:(nonnull NSUUID *)receiptID                                                     success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse  * _Nullable response, UIImage *responseObject))success                                                     failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { __block NSURLSessionDataTask *task = nil; dispatch_sync(self.synchronizationQueue, ^{/// 串行队列     NSString *URLIdentifier = request.URL.absoluteString;     if (URLIdentifier == nil) {/// 进一步判断下载地址是否为空,         if (failure) {             NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];             dispatch_async(dispatch_get_main_queue(), ^{                 failure(request, nil, error);             });         }         return;     }     AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];     if (existingMergedTask != nil) {         AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];         [existingMergedTask addResponseHandler:handler];         task = existingMergedTask.task;         return;     }     /**进一步判断请求的缓存类型*/     switch (request.cachePolicy) {         case NSURLRequestUseProtocolCachePolicy:         case NSURLRequestReturnCacheDataElseLoad:         case NSURLRequestReturnCacheDataDontLoad: {/// 只加载内存里面的数据             UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];             if (cachedImage != nil) {                 if (success) {                     dispatch_async(dispatch_get_main_queue(), ^{                         success(request, nil, cachedImage);                     });                 }                 return;             }             break;         }         default:             break;     }     NSUUID *mergedTaskIdentifier = [NSUUID UUID];     NSURLSessionDataTask *createdTask;     __weak __typeof__(self) weakSelf = self;      createdTask = [self.sessionManager                    dataTaskWithRequest:request                    completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {                        dispatch_async(self.responseQueue, ^{                            __strong __typeof__(weakSelf) strongSelf = weakSelf;                             /*根据url来从组合字典里面取出对应的mergedTask*/                            AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];                            if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {/// 相等                               /**将当前的mergedTask根据url从mergedTasks字典里面移除*/                                mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];                                if (error) {/// 下载出现错误的时候                                    /**当图片设置并发的加载的时候,就会一个组合任务里面会有多个handle*/                                    for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {                                        if (handler.failureBlock) {                                            /**回到主线程回掉block*/ dispatch_async(dispatch_get_main_queue(), ^{                                                handler.failureBlock(request, (NSHTTPURLResponse*)response, error);                                            });                                        }                                    }                                } else {                                    /**将下载好的图片添加到内存中*/                                    [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];                                     for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {                                        if (handler.successBlock) {                                            dispatch_async(dispatch_get_main_queue(), ^{                                                handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);                                            });                                        }                                    }                                                                    }                            }                            /**活跃的次数减1*/                            [strongSelf safelyDecrementActiveTaskCount];                            /**安全的开始下一个请求*/                            [strongSelf safelyStartNextTaskIfNecessary];                        });                    }];     /**根据UUID来穿件响应的hander*/     AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];     /**将下载的task和UUID以及URL共同创建出来MergedTask*/     AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]                                                initWithURLIdentifier:URLIdentifier                                                identifier:mergedTaskIdentifier                                                task:createdTask];     /**并将handle添加到MergedTask中*/     [mergedTask addResponseHandler:handler];     /**并将合并任务添加到单例对象的mergedTasks字典中,并且已url作为key*/     self.mergedTasks[URLIdentifier] = mergedTask;     /**判断请求的个数是否大于最大的请求个数*/     if ([self isActiveRequestCountBelowMaximumLimit]) {         /**开始任务请求,并将活跃的次数加一*/         [self startMergedTask:mergedTask];     } else {         [self enqueueMergedTask:mergedTask];     }      task = mergedTask.task; });  if (task) {     return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];   } else {     return nil;   } } 

AFAutoPurgingImageCache《单例创建》 管理缓存数据

- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { dispatch_barrier_async(self.synchronizationQueue, ^{     AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];      AFCachedImage *previousCachedImage = self.cachedImages[identifier];     if (previousCachedImage != nil) {         self.currentMemoryUsage -= previousCachedImage.totalBytes;     }      self.cachedImages[identifier] = cacheImage;     self.currentMemoryUsage += cacheImage.totalBytes; }); /**使用栅栏来截断当前的异步请求,来判断设置的缓存大小和总缓存大小比较*/ dispatch_barrier_async(self.synchronizationQueue, ^{     if (self.currentMemoryUsage > self.memoryCapacity) {         UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;         NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];         /**创建一个需要根据key排序的对象*/         /**创建一个根据key=lastAccessDate的字段进行排序,yes表示升序,NO表示降序*/         NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" ascending:YES];         [sortedImages sortUsingDescriptors:@[sortDescriptor]];          UInt64 bytesPurged = 0;          for (AFCachedImage *cachedImage in sortedImages) {             [self.cachedImages removeObjectForKey:cachedImage.identifier];             bytesPurged += cachedImage.totalBytes;             if (bytesPurged >= bytesToPurge) {                 break ;             }         }         self.currentMemoryUsage -= bytesPurged;       }     }); }