美文网首页
SDWebImage 4.x版本源码分析(三)SDWebImag

SDWebImage 4.x版本源码分析(三)SDWebImag

作者: 快乐的老船长 | 来源:发表于2018-03-21 12:40 被阅读236次

    可以来这里下载一下源码注释

    4.SDWebImageDownloader

    问题:

    ①. clang diagnostic 是什么?
    ②. 添加监听前,为什么要先移除监听?
    ③. 为什么用单例?何时需要用单例???
    ④. SDWebImageDownloadToken的用途?

    枚举

    //下载选项
    typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
        SDWebImageDownloaderLowPriority = 1 << 0,
        SDWebImageDownloaderProgressiveDownload = 1 << 1,
        SDWebImageDownloaderUseNSURLCache = 1 << 2,
        SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
        SDWebImageDownloaderContinueInBackground = 1 << 4,
        SDWebImageDownloaderHandleCookies = 1 << 5,
        SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
        SDWebImageDownloaderHighPriority = 1 << 7,
        SDWebImageDownloaderScaleDownLargeImages = 1 << 8,
    };
    
    //下载执行的顺序
    typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
        SDWebImageDownloaderFIFOExecutionOrder,
        SDWebImageDownloaderLIFOExecutionOrder
    };
    

    .h文件中的属性

     //是否解压图片
    @property (assign, nonatomic) BOOL shouldDecompressImages;
     //设置最大并发数量
    @property (assign, nonatomic) NSInteger maxConcurrentDownloads;
     //获取当前下载的数量
    @property (readonly, nonatomic) NSUInteger currentDownloadCount;
    //下载时间 默认15秒
    @property (assign, nonatomic) NSTimeInterval downloadTimeout;
     //NSURLSession配置一些请求所需要的策略
    @property (readonly, nonatomic, nonnull) NSURLSessionConfiguration *sessionConfiguration;
     //设置下载顺序
    @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;
    
     //生成单例 并返回当前实例
    + (nonnull instancetype)sharedDownloader;
    
    //设置身份认证
    @property (strong, nonatomic, nullable) NSURLCredential *urlCredential;
     //设置用户名
    @property (strong, nonatomic, nullable) NSString *username;
    //设置密码
    @property (strong, nonatomic, nullable) NSString *password;
    
     //针对header进行过滤的block
    @property (nonatomic, copy, nullable) SDWebImageDownloaderHeadersFilterBlock headersFilter;
    

    .m中的属性

    //定义下载队列
    @property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue;
    //定义下载的上个operation 作用是为了后面的下载依赖
    @property (weak, nonatomic, nullable) NSOperation *lastAddedOperation;
    
    // 图片下载操作类
    @property (assign, nonatomic, nullable) Class operationClass;
    //下载url作为key value是具体的下载operation 用字典来存储,方便cancel等操作
    @property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, SDWebImageDownloaderOperation *> *URLOperations;
    
    //HTTP请求头
    @property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *HTTPHeaders;
    
    //保证线程安全设置的信号量
    @property (strong, nonatomic, nonnull) dispatch_semaphore_t operationsLock; // a lock to keep the access to `URLOperations` thread-safe
    @property (strong, nonatomic, nonnull) dispatch_semaphore_t headersLock; // a lock to keep the access to `HTTPHeaders` thread-safe
    
    // The session in which data tasks will run
    @property (strong, nonatomic) NSURLSession *session;
    

    .h中的方法

    //生成一个实例,利用特定的配置sessionConfiguration
    - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER;
    
     //针对request添加HTTP header
    - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field;
    
     //返回某个header field的value
    - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field;
    
     //设置一个SDWebImageDownloaderOperation的子类赋值给_operationClass
    - (void)setOperationClass:(nullable Class)operationClass;
    
    //根据指定的url异步加载图片
    - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                       options:(SDWebImageDownloaderOptions)options
                                                      progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                     completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
    
    //取消指定token的下载
    - (void)cancel:(nullable SDWebImageDownloadToken *)token;
     //设置下载队列是否挂起
    - (void)setSuspended:(BOOL)suspended;
     //取消所有的下载
    - (void)cancelAllDownloads;
    
     //强制给self设置一个新的NSURLSession
    - (void)createNewSessionWithConfiguration:(nonnull NSURLSessionConfiguration *)sessionConfiguration;
    
     //取消operation并且session设置为Invalidates
    - (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations;
    

    .m中的方法

    //init和dealloc
    + (void)initialize
    + (nonnull instancetype)sharedDownloader
    - (nonnull instancetype)init
    - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration
    - (void)createNewSessionWithConfiguration:(NSURLSessionConfiguration *)sessionConfiguration
    - (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations
    - (void)dealloc
    
    //setter和getter方法
    - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field
    - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field
    - (nonnull SDHTTPHeadersDictionary *)allHTTPHeaderFields
    - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads
    - (NSUInteger)currentDownloadCount
    - (NSInteger)maxConcurrentDownloads
    - (NSURLSessionConfiguration *)sessionConfiguration
    - (void)setOperationClass:(nullable Class)operationClass
    
    //下载和取消下载
    - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                       options:(SDWebImageDownloaderOptions)options
                                                      progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                     completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock
    - (void)cancel:(nullable SDWebImageDownloadToken *)token
    - (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock
                                               completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock
                                                       forURL:(nullable NSURL *)url
                                               createCallback:(SDWebImageDownloaderOperation *(^)(void))createCallback
    - (void)setSuspended:(BOOL)suspended
    - (void)cancelAllDownloads
    - (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task
    

    这个类具体做了什么呢,首先看下+ (void)initialize方法

    + (void)initialize
    {
        if (NSClassFromString(@"SDNetworkActivityIndicator")) {
            //clang diagnostic 是什么用途???
    
            //为了让 SDNetworkActivityIndicator 文件可以不用导入项目中来(如果不需要的话),这里使用了 runtime 的方式来实现动态创建类以及调用方法,如果导入了这个类,就能设置 Network Activity Indicator,如果没有导入,就不用管他,但也能编译通过
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    
            id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
    
    #pragma clang diagnostic pop
    
            //移除通知观察者。以防它之前被添加。 
            //再添加通知观察者。
        }
    }
    

    +shareDownloader 方法调用- init创建了一个单例,在-init方法中,调用了-initWithSessionConfiguration和-createNewSessionWithConfiguration来进行一些初始化和默认值设置,如 创建session,设置默认下载超时时长 15s,OperationQueue的最大并发数为6等

    SDWebImageDownloader中,最核心的方法是downloadImageWithURLoptions 方法,我们来具体看下

    - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                       options:(SDWebImageDownloaderOptions)options
                                                      progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                     completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock 
    {
       1.调用addProgressCallback方法 return token,addProgressCallback的回调里进行以下操作
        {
            1.1设置下载时间
            1.2创建request
            1.3创建operation对象 传入 request session options
            1.4设置身份认证
            1.5设置下载优先级
            1.6设置下载顺序
        }
    }
    

    原来这个方法里只调用了addProgressCallback方法,那么 addProgressCallback 究竟做了哪些事情?

    - (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock
                                               completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock
                                                       forURL:(nullable NSURL *)url
                                               createCallback:(SDWebImageDownloaderOperation *(^)(void))createCallback 
    {
        1.生成URLOperations字典 下载url作为key value是具体的下载operation
        2.将操作添加到操作队列中
        3.将进度progressBlock和下载结束completedBlock封装成字典SDCallbacksDictionary,装入数组callbackBlocks,
        4.生成token标识,并返回token
    }
    

    流程图:

    image.png

    相关文章

      网友评论

          本文标题:SDWebImage 4.x版本源码分析(三)SDWebImag

          本文链接:https://www.haomeiwen.com/subject/wxzwqftx.html