Sdwebimage Source Code Analysis (I.)

Source: Internet
Author: User

In the process of developing the project will use a lot of third-party libraries, such as Afnetworking,sdwebimage,fmdb, but has not been to a good study, recently just the project is not too tight, idle can give themselves charge, first study the sdwebimage of the bottom realization, Source Address: Sdwebimage
To introduce sdwebimage, we use more of the Uiimageview classification that it provides, which supports downloading and caching images from remote servers. Since iOS5.0 started, Nsurlcache can also handle disk caching, so what is the advantage of sdwebimage? The first nsurlcache is to cache raw data to disk or memory, so the raw data needs to be converted into specific objects, such as UIImage, for each use, resulting in additional data parsing and memory usage, While Sdwebimage is the cache UIImage object in memory, slow presence nscache, while directly saving the compressed image to disk; Another problem is that when you first use the Image object in Uiimageview, the decoding of the image is run in the main thread! Instead, Sdwebimage forces the decoding operation to be placed in the child thread. is the sdwebimage simple class diagram relationship:


Sdwebimage.png

Below from Uiimageview's picture loading began to look, let ' s go!

First we'll call the method when we set up the picture for Uiimageview:

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;

Where the URL is the address of the remote picture, and placeholder is the pre-displayed picture.
In fact, you can add some additional parameters, than the slice option sdwebimageoptions

typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {    

General use of sdwebimageretryfailed | Sdwebimagelowpriority, here's a look at the specific function call:

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {    [self sd_cancelCurrentImageLoad];//取消正在下载的操作    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);//关联该view对应的图片URL     /*...*/     if (url) {        __weak UIImageView *wself = self;//防止retain cricle        //由SDWebImageManager负责图片的获取        id  operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {              /*获取图片到主线层显示*/         }];        [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];    } }

You can see that the image is managed by Sdwebimagemanager from the server, memory, or hard drive, and this class has several important properties:

@property (strong, nonatomic, readwrite) SDImageCache *imageCache;//负责管理cache,涉及内存缓存和硬盘保存@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader;//负责从网络下载图片@property (strong, nonatomic) NSMutableArray *runningOperations;//包含所有当前正在下载的操作对象

The manager will find the corresponding image according to the URL first to Imagecache, if not in the use of downloader to download, and in the download to complete the cache image to Imagecache, and then see the implementation:

-(ID) Downloadimagewithurl: (nsurl *) URL options: (sdwebimageoptions) Options Progres S: (Sdwebimagedownloaderprogressblock) Progressblock completed: (SDWEBIMAGECOMPLETIONWI    Thfinishedblock) Completedblock {/*...*///generate corresponding key based on URL, no special handling for [url absolutestring];    NSString *key = [self cachekeyforurl:url]; Go to Imagecache for pictures operation.cacheoperation = [Self.imagecache querydiskcacheforkey:key done:^ (UIImage *image, Sdimagecachetype cachetype) {/*...*///If the picture is not found, or if the sdwebimagerefreshcached option is used, download the If from the network (!image || Options & sdwebimagerefreshcached) && (![ Self.delegate respondstoselector: @selector (imagemanager:shoulddownloadimageforurl:)] | | [Self.delegate imagemanager:self Shoulddownloadimageforurl:url])) {Dispatch_main_sync_safe (^{///If the picture is found, but the sdwebimagerefreshcached option is used, the notification gets to the picture and is downloaded again from the network, so that n Surlcache re-refresh CompletedbloCK (image, Nil, cachetype, YES, URL);            }); }/* Download option settings *///Use Imagedownloader to turn on network download id suboperation = [self.imagedownloader download Imagewithurl:url options:downloaderoptions progress:progressblock completed:^ (UIImage *downloadedimage, NSData *data                     , Nserror *error, BOOL finished) {/*...*/if (downloadedimage && finished) { After the download is complete, save the picture to Imagecache, and then the main thread returns to the [Self.imagecache storeimage:downloadedimage Recalculat                        Efromimage:no imagedata:data Forkey:key Todisk:cacheondisk];                                } dispatch_main_sync_safe (^{if (!weakoperation.iscancelled) {                            Completedblock (Downloadedimage, Nil, sdimagecachetypenone, finished, URL);                    }                        });        }}/*...*/} else if (image) {  The image is found in the cache and is returned directly to Dispatch_main_sync_safe (^{if (!weakoperation.iscancelled) {                Completedblock (image, Nil, cachetype, YES, URL);        }            });    }    }]; return operation;}

See downloader from the network download process, the download is placed in Nsoperationqueue, the default maxconcurrentoperationcount is 6,timeout time is 15s:

-(ID <SDWebImageOperation>) Downloadimagewithurl: (nsurl *) URL options: (sdwebimagedownloaderoptions) options Progress: (Sdwebimagedownloaderprogressblock) Progressblock completed: (sdwebimagedownloadercompletedblock)    Completedblock {__block sdwebimagedownloaderoperation *operation;    __weak Sdwebimagedownloader *wself = self; /*...*///Prevent Nsurlcache and Sdimagecache repeat cache nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] InitWithURL:url CachePolicy: (Options & Sdwebimagedownloaderusensurlcache?)    Nsurlrequestuseprotocolcachepolicy:nsurlrequestreloadignoringlocalcachedata) TimeoutInterval:timeoutInterval]; Request.    Httpshouldhandlecookies = (options & sdwebimagedownloaderhandlecookies); Request.    httpshouldusepipelining = YES; Request.allhttpheaderfields = wself. httpheaders;//set HTTP header//sdwebimagedownloaderoperation derived from nsoperation, responsible for picture download work operation = [[                                        Sdwebimagedownloaderoperation Alloc] Initwithrequest:request                  Options:options progress:^ (Nsinteger receivedsiz E, Nsinteger expectedsize) {} completed:^ (UIImage *image, NSData *d    ATA, Nserror *error, BOOL finished) {} cancelled:^{}]; Operation.shoulddecompressimages = wself.shoulddecompressimages;//If you need to decode if (Wself.username && Wself.password) {operation.credential = [nsurlcredential credentialWithUser:wself.username password:wself.pass    Word persistence:nsurlcredentialpersistenceforsession]; } if (options & sdwebimagedownloaderhighpriority) {operation.queuepriority = Nsoperationqueuepriorityhi        gh } else if (Options & sdwebimagedownloaderlowpriority) {operation.queuepriority = Nsoperationqueuepriorityl    ow        } [Wself.downloadqueue addoperation:operation]; if (Wself.executionorder = = SdweBimagedownloaderlifoexecutionorder) {//If the download order is added later, run first [wself.lastaddedoperation Adddependency:ope            Ration];        wself.lastaddedoperation = operation;    }    }]; return operation;}

Sdwebimagedownloaderoperation is derived from nsoperation, and the download of the picture is done through nsurlconnection, in order to ensure that the downloaded data is processed, the Runloop is run in the background:

-(void) Start {/*...*/#if target_os_iphone && __iphone_os_version_max_allowed >= __iphone_4_0//Open Background download            if ([self shouldcontinuewhenappentersbackground]) {__weak-__typeof__ (self) wself = self; Self.backgroundtaskid = [[uiapplication sharedapplication] beginbackgroundtaskwithexpirationhandler:^{__st                Rong __typeof (wself) sself = wself;                    if (sself) {[sself cancel];                    [[UIApplication sharedapplication] endBackgroundTask:sself.backgroundTaskId];                Sself.backgroundtaskid = Uibackgroundtaskinvalid;        }            }];        } #endif self.executing = YES;    Self.connection = [[Nsurlconnection alloc] initWithRequest:self.request delegate:self Startimmediately:no];    } [self.connection start];        if (self.connection) {if (Self.progressblock) {self.progressblock (0, nsurlresponseunknownlength); }//Register and send notificationsRequired on a thread Dispatch_async (Dispatch_get_main_queue (), ^{[[Nsnotificationcenter Defaultcenter] Postnotificat        Ionname:sdwebimagedownloadstartnotification Object:self];       }); Cfrunlooprun ()///Run the current Runlooprun in default mode until the call Cfrunloopstop stop running if (!self.isfinished) {[Self.connection can            CEL]; [Self connection:self.connection didfailwitherror:[nserror errorwithdomain:nsurlerrordomain code:        Nsurlerrortimedout Userinfo:@{nsurlerrorfailingurlerrorkey:self.request.url}]; }} #if target_os_iphone && __iphone_os_version_max_allowed >= __iphone_4_0 if (self.backgroundtaskid! = U        Ibackgroundtaskinvalid) {[[UIApplication sharedapplication] endBackgroundTask:self.backgroundTaskId];    Self.backgroundtaskid = Uibackgroundtaskinvalid; } #endif}

During the download process, the agent-(void) connection: (nsurlconnection  ) connection didreceivedata: (nsdata  ) Data will be saved to Nsmutabledata, [Self.imagedata Appenddata:data], after the download is complete, the image is decoded in the thread, and imagecache the cache in the completed Completionblock:

-(void) connectiondidfinishloading: (nsurlconnection *) aconnection {Sdwebimagedownloadercompletedblock    Completionblock = Self.completedblock; @synchronized (self) {cfrunloopstop (cfrunloopgetcurrent ());//Stop the current Runloop/*...*/if (completionblock            ) {/*...*/UIImage *image = [UIImage sd_imageWithData:self.imageData];            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) { Image = [UIImage decodedimagewithimage:image];//picture Decoding}} if (Cgsi Zeequaltosize (Image.size, Cgsizezero)) {Completionblock (nil, nil, [Nserror errorwithdomain:@ "Sdwebimageerr   Ordomain "code:0 Userinfo:@{nslocalizeddescriptionkey: @" Downloaded image has 0 pixels "}], YES);         } else {Completionblock (image, Self.imagedata, nil, YES);    }}} Self.completionblock = nil; [self-done];}

Follow the image cache can be consulted: Sdwebimage source Analysis (ii)

Sdwebimage Source Code Analysis (I.)

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.