Sdwebimage Source Code Analysis

Source: Internet
Author: User
Tags webp

Version: 3.7

Sdwebimage is an open source third-party library that provides a taxonomy of Uiimageview to support the ability to download and cache pictures from remote servers. It has the following functions: Provides a classification of Uiimageview to support the loading and caching of network pictures an asynchronous picture loader an asynchronous memory + disk picture cache support GIF image support WEBP picture background Image Decompression processing ensure that the same URL picture is not downloaded multiple times Ensure that false URLs are not repeatedly loaded and that the main thread is not blocked when downloading and caching

From GitHub on the use of sdwebimage can be seen, sdwebimage in the image download and cache processing is still very recognized. In this article, we mainly from the source point of view to analyze the implementation mechanism of sdwebimage. The discussion will focus on the download and caching of images, not the support for GIF images and WEBP images. Download

In Sdwebimage, the download of the picture is done by the Sdwebimagedownloader class. It is an asynchronous downloader, and the image loading is optimized for processing. Let's take a look at the specifics of its implementation. Download Options

During the download process, the program performs different actions depending on the different download options that are set. The download option is defined by the enumeration sdwebimagedownloaderoptions, as follows

typedef ns_options (Nsuinteger, sdwebimagedownloaderoptions) {sdwebimagedownloaderlowpriority = 1 << 0, SDWebIma Gedownloaderprogressivedownload = 1 << 1,//The request does not use Nsurlcache by default, and if this option is set, the Nsurlcache is used with the default cache policy Sdwebimagedown Loaderusensurlcache = 1 << 2,//If the picture is read from the Nsurlcache cache, use nil as a parameter to invoke the completion block SDWEBIMAGEDOWNLOADERIGNORECACHEDRESP Onse = 1 << 3,//on iOS 4+ system, allow the program to continue downloading pictures after it has entered the background. This operation completes the background download by requesting additional time from the system. If the background task terminates, the operation is canceled sdwebimagedownloadercontinueinbackground = 1 << 4,//by setting Nsmutableurlrequest.httpshouldhandle Cookies = yes to handle cookies stored in Nshttpcookiestore sdwebimagedownloaderhandlecookies = 1 << 5,//Allow untrusted SSL certificates.
  Mainly used for testing purposes.  Sdwebimagedownloaderallowinvalidsslcertificates = 1 << 6,//Picture download is placed in high priority queue Sdwebimagedownloaderhighpriority = 1 << 7,};

As you can see, these options mainly involve the priority of the download, caching, background task execution, cookie processing to certify several aspects. Download Order

The download operation for Sdwebimage is processed in a sequential order, and it defines two download sequences, as shown below

typedef ns_enum (Nsinteger, Sdwebimagedownloaderexecutionorder) {
  //In the form of a queue, downloaded in FIFO order. This is the default download order
  Sdwebimagedownloaderfifoexecutionorder,
  //In the form of a stack, in the order of LIFO.
  Sdwebimagedownloaderlifoexecutionorder
};

Download Manager

Sdwebimagedownloader Download Manager is a singleton class that is primarily responsible for the management of image download operations. The download of the picture is done in a nsoperationqueue operation queue, which is declared as follows:

@property (Strong, nonatomic) Nsoperationqueue *downloadqueue;

By default, the maximum number of concurrent queues is 6. If necessary, we can modify it by Sdwebimagedownloader the Maxconcurrentdownloads property of the class.

The network response serialization for all download operations is handled in a custom parallel dispatch queue, with the following declarations and definitions:

@property (Sddispatchqueuesettersementics, nonatomic) dispatch_queue_t barrierqueue;
-(ID) init {
  if (self = [super init]) {
    ...
    _barrierqueue = Dispatch_queue_create ("Com.hackemist.SDWebImageDownloaderBarrierQueue", dispatch_queue_concurrent );
    ...
  }
  return self;
}

Each image download will correspond to some callback actions, such as download progress callback, download completion callback, and so on, these callback operations are presented in block form, for which a few blocks are defined in SDWebImageDownloader.h, as follows:

Download Progress
typedef void (^sdwebimagedownloaderprogressblock) (Nsinteger receivedsize, Nsinteger expectedsize);
Download complete
typedef void (^sdwebimagedownloadercompletedblock) (UIImage *image, NSData *data, Nserror *error, BOOL finished);
Header Filter
typedef nsdictionary * (^sdwebimagedownloaderheadersfilterblock) (Nsurl *url, nsdictionary *headers);

These callback information for picture download is stored in the Urlcallbacks property of the Sdwebimagedownloader class, which is a dictionary, the key is the URL address of the picture, and value is an array that contains multiple sets of callback information for each picture. Since we allow multiple images to be downloaded at the same time, there may be multiple threads operating the Urlcallbacks property at the same time. To ensure thread safety for urlcallbacks operations (Add, remove), Sdwebimagedownloader put these operations as a task into the Barrierqueue queue. and set the barrier to ensure that only one thread at a time operates the Urlcallbacks property, let's take the add operation as an example, as shown in the following code:

-(void) Addprogresscallback: (sdwebimagedownloaderprogressblock) Progressblock Andcompletedblock: ( Sdwebimagedownloadercompletedblock) Completedblock Forurl: (nsurl *) URL createcallback: (sdwebimagenoparamsblock) Createcallback {...//1. Dispatch_barrier_sync operation to ensure that only one thread can operate on urlcallbacks at the same time dispatch_barrier_sync (self. Barrierqueue, ^{...//2. A single download of the synchronous download request that processes the same URL nsmutablearray *callbacksforurl = self.
  Urlcallbacks[url];
  Nsmutabledictionary *callbacks = [Nsmutabledictionary new];
  if (progressblock) callbacks[kprogresscallbackkey] = [Progressblock copy];
  if (completedblock) callbacks[kcompletedcallbackkey] = [Completedblock copy];
  [Callbacksforurl Addobject:callbacks]; Self.
  Urlcallbacks[url] = Callbacksforurl;
...
    }); }

The entire download Manager's management of download requests is handled in the downloadImageWithURL:options:progress:completed: method, The method invokes the AddProgressCallback:andCompletedBlock:forURL:createCallback: method mentioned above to store the requested information in the manager and create a new operation in the block that created the callback. The configuration then puts it into the downloadqueue operation queue, and the last method returns the newly created operation. The specific implementation is as follows:

-(ID <SDWebImageOperation>) Downloadimagewithurl: (nsurl *) URL options: (sdwebimagedownloaderoptions) options Progress: (Sdwebimagedownloaderprogressblock) Progressblock completed: (sdwebimagedownloadercompletedblock)
  Completedblock {... [Self addprogresscallback:progressblock andcompletedblock:completedblock forurl:url createCallback:^{...//1. Create Request the object and set its properties according to the options parameter//In order to avoid potential duplicate caches (Nsurlcache + sdimagecache), disable cache operation for picture requests if no explicit notification is required nsmutableurlrequest *re Quest = [[Nsmutableurlrequest alloc] initwithurl:url cachepolicy: (Options & Sdwebimagedownloaderusensurlcache?
    Nsurlrequestuseprotocolcachepolicy:nsurlrequestreloadignoringlocalcachedata) TimeoutInterval:timeoutInterval]; ...//2. Create a Sdwebimagedownloaderoperation Action object and make configuration//configuration information including whether authentication is required, priority operation = [[Wself.operationclass alloc] Initwithre Quest:request options:options progress:^ (Nsinteger receivedsize , Nsinteger Expectedsize) {//3. Find all progress-processing callbacks for the URL from the manager's Callbacksforurl and call ... For (Nsdictionary *callbacks in Callbacksforurl) {Sdwebimagedo
                                 Wnloaderprogressblock callback = Callbacks[kprogresscallbackkey];
                               if (callback) callback (Receivedsize, expectedsize); }} completed:^ (UIImage *image, NSData *data, Nserror *error, BOO
                               L finished) {//4. From the manager's Callbacksforurl, find all the completion processing callbacks for the URL and call If finished is yes, the callback information corresponding to the URL is removed from urlcallbacks ... if (finis
                              hed) {[Sself removecallbacksforurl:url];
                     } for (Nsdictionary *callbacks in Callbacksforurl) {           Sdwebimagedownloadercompletedblock callback = Callbacks[kcompletedcallbackkey];
                              if (callback) callback (image, data, error, finished); }} cancelled:^{//5. The cancel operation will return the URL corresponding to the
                              Remove Sdwebimagedownloader *sself = wself from urlcallbacks;
                              if (!sself) return;
                            [Sself Removecallbacksforurl:url];
    }]; ...//6. Add the operation to the action queue Downloadqueue//If it is a LIFO order, the new operation is dependent on the last operation in the original queue, and the new action is set to the last action [Wself.downloadqueue addoperation:oper
    Ation]; if (Wself.executionorder = = Sdwebimagedownloaderlifoexecutionorder) {[Wself.lastaddedoperation AddDependency:operat
      ION];
    wself.lastaddedoperation = operation;
  }
  }];
return operation;

 }

In addition, the time-out for each download operation can be set by the Downloadtimeout property, with a default value of 15 seconds. Download Operation

Each picture is downloaded as a operation operation. We have analyzed the creation of this operation and the process of joining the Operation queue. Now let's take a look at the specific implementation of a single operation.

Sdwebimage defines a protocol, sdwebimageoperation, as the underlying protocol for image download operations. It only declares a Cancel method, which is used to cancel the operation. The specific statement of the agreement is as follows:

@protocol sdwebimageoperation <NSObject>

-(void) cancel;

@end

Sdwebimage has customized a operation class, which is

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.