SDWebImage source code learning, sdwebimage source code

Source: Internet
Author: User
Tags ssl certificate

SDWebImage source code learning, sdwebimage source code
Preface

In my personal understanding, SDWebImage is a great open-source framework that helps us load images asynchronously and cache these images to memory and disk. In fact, there are also many powerful functions for us to use. If we are proficient in using their APIs, we can achieve a lot of complicated requirements.

Github latest: https://github.com/rs/SDWebImage

Next, we will start to learn about this framework.

Body

Since I downloaded the latest version, I learned everything from it.

First look at the next method:

[_ ImageView2 progress: url2 placeholderImage: image2 options: SDWebImageRetryFailed progress: ^ (NSInteger receivedSize, NSInteger expectedSize) {NSLog (@ "processing the download progress ");} completed: ^ (UIImage * image, NSError * error, SDImageCacheType cacheType, NSURL * imageURL) {NSLog (@ "something done after image loading");}];

This is the most comprehensive method. You can also see that many methods for downgrading SDWebImage directly call this method. Other methods are not recorded.

About parameters: 1. sd_setImageWithURL: image url

2. placeholderImage: placeholder image (the image displayed when the image is not fully loaded or optional)

3. options: provides a loading mechanism. Default Value: SDWebImageRetryFailed. For more information, see.

// Retry SDWebImageRetryFailed = 1 <0, // download starts during UI interaction, resulting in delayed download such as UIScrollView slowing down. SDWebImageLowPriority = 1 <1, // only perform memory cache SDWebImageCacheMemoryOnly = 1 <2, // this flag can be downloaded progressively, the displayed image is gradually downloaded from SDWebImageProgressiveDownload = 1 <3, // refresh the cache SDWebImageRefreshCached = 1 <4, // download SDWebImageContinueInBackground = 1 <5, // NSMutableURLRequest. HTTPShouldHandleCookies = YES; SDWebImageHandleCookies = 1 <6, // Invalid SSL certificate is allowed // SDWebImageAllowInvalidSSLCertificates = 1 <7, // download SDWebImageHighPriority = 1 <8, // latency placeholder SDWebImageDelayPlaceholder = 1 <9, // modify the animation image SDWebImageTransformAnimatedImage = 1 <10,

4. progress: Check the name and parameters to understand the role of the block.

5. completed: the callback block after the image is loaded. The parameter describes SDImageCacheType, which is also an enumeration. Through this enumeration, we can see where the loaded image is loaded (cached, three types are provided: SDImageCacheTypeNone has no cache type, that is

SDImageCacheTypeDisk is cached by the hard disk

SDImageCacheTypeMemory comes from memory cache

Next let's look at the internal implementation:

1. Before this step, we should first learn a "association" based on the runtime mechanism, because it is used in many places.

1. Establish Association:

Method: objc_setAssociatedObject (id object, const void * key, id value, objc_AssociationPolicy policy)

Introduction parameter: object source object

Key: the unique static variable key. Note: This parameter is a pointer.

Object associated with value

Policy Association policy: indicates whether the related objects are associated by assigning values, retaining references, or replicating objects, and whether such associations are atomic or non-atomic objects.

My personal understanding is that this method is used to associate the value object with the object through the key keyword and policy Association policy. (In this case, the life cycle of the value object is linked to the object based on the association policy. For example, an association policy OBJC_ASSOCIATION_RETAIN_NONATOMIC is used in SDWebImage. If you see RETAIN, you should know that even if we release the value object, we can still access the value object if the object is not release. Furthermore, when an object exists, the value object must exist. Unless we cancel the association .)

2. Get the associated object

Method: objc_getAssociatedObject (id object, const void * key)

The parameter is not described. You can find the associated method above. However, this method returns a value type object.

To sum up, let's talk about the theory. The associated object exists because the attribute value cannot be added during expansion. It exists in the form of a global dictionary, and the index is the key you pass. This method is used to simulate binding of Object-oriented Data to operations. In fact, I personally think that this is used here because most image requests are carried out in batches and request methods are repeatedly called. If there is no global manager to manage these requests, this will inevitably result in very passive and performance consumption. Therefore, the author uses this method here to remove the current operation managed by the manager to cancel to reduce unnecessary load. To improve the performance of the framework.

Ii. Internal implementation process of SDWebImage

1. Entry: UIImageView + WebCache first cancels other downloading operations in the queue through association, and then displays the placeholder image. Method:

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock 

 

2. SDWebImageManager performs image request operations by passing url and other parameters. Method:

- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionWithFinishedBlock)completedBlock

3. first, judge the uploaded url. If the url is empty or a failed url has been requested and the option is SDWebImageRetryFailed (request again after failure, the system directly calls back the failed completedBlock (nil, error, SDImageCacheTypeNone, YES, url) and returns the error message (NSURLErrorFileDoesNotExist ). Code:

 1    BOOL isFailedUrl = NO; 2     @synchronized (self.failedURLs) { 3         isFailedUrl = [self.failedURLs containsObject:url]; 4     } 5      6     if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { 7         dispatch_main_sync_safe(^{ 8             NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; 9             completedBlock(nil, error, SDImageCacheTypeNone, YES, url);10         });11         return operation;12     }

 

4. Use urlKey in SDImageCache to check whether the image in the cache has been downloaded. Method:

- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock

 

5. it will be first searched in the memory image cache and then called back to doneBlock (image, SDImageCacheTypeMemory) to SDWebImageManager, SDWebImageManager and then called back completedBlock (image, nil, cacheType, YES, url) display the image at the front end of UIImageView + WebCache. Code:

1   UIImage *image = [self imageFromMemoryCacheForKey:key];2   if (image) {3      doneBlock(image, SDImageCacheTypeMemory);4      return nil;5   }

 

6. If the image is not found in the memory cache, NSOperation is generated to search for the image on the hard disk based on the urlKey to see if the image has been cached. If an image is read from the hard disk, add the image to the memory cache (if the idle memory is too small, the memory cache will be cleared first ). Because this step is performed in NSOperation, The result callback doneBlock (diskImage, SDImageCacheTypeDisk) must be performed back to the main thread ). Then SDWebImageManager calls back completedBlock (image, nil, cacheType, YES, url) to display the image at the front end of UIImageView + WebCache. Code:

 1     NSOperation *operation = [NSOperation new]; 2     dispatch_async(self.ioQueue, ^{ 3         if (operation.isCancelled) { 4             return; 5         } 6  7         @autoreleasepool { 8             UIImage *diskImage = [self diskImageForKey:key]; 9             if (diskImage) {10                 NSUInteger cost = SDCacheCostForImage(diskImage);11                 [self.memCache setObject:diskImage forKey:key cost:cost];12             }13 14             dispatch_async(dispatch_get_main_queue(), ^{15                 doneBlock(diskImage, SDImageCacheTypeDisk);16             });17         }18     });

7. If no image is found in the memory or hard disk cache, You need to download the image. The download method of SDWebImageDownloader is called. Method:

- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock

 

8. The downloading process is really complicated, and it's hard to see the current capabilities. The following content is taken from the network and can be viewed and supplemented later.

Share or regenerate a download tool SDWebImageDownloader to download images. The NSURLConnection method is used to download images. The delegate method is used to determine whether the images are being downloaded, completed, and failed to be downloaded. Connection: didReceiveData: The ImageIO is used to load data according to the image download progress. ConnectionDidFinishLoading: After the data is downloaded, it is sent to SDWebImageDecoder for image decoding. The image decoding process is completed in an NSOperationQueue, and the main thread UI is not slowed down. If you need to process the downloaded image twice, it is better to do so here, which will be much more efficient. In the main thread yydelegateonmainthreadwithinfo: the decoding is completed, and imageDecoder: didFinishDecodingImage: userInfo: calls back to SDWebImageDownloader. ImageDownloader: didFinishWithImage: calls back to SDWebImageManager to notify the image download is complete. This notification notifies all downloadDelegates that the download is complete and calls back to display the image to the desired location. Save the image to SDImageCache, and save both the memory cache and the hard disk cache. Writing files to the hard disk is also completed in separate NSInvocationOperation to Avoid dragging the main thread slowly. SDImageCache registers some message notifications during initialization. It cleans up the memory image cache when the memory is warned or returned to the background, and clears expired images when the application ends. SDWI also provides UIButton + WebCache and MKAnnotationView + WebCache for ease of use. SDWebImagePrefetcher can download images in advance for later use.

Related Article

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.