In the image loading framework of iOS, SDWebImage occupies a large part of the market. It can download and cache images from the network and set images to the corresponding UIImageView control or UIButton control. Using SDWebImage to manage image loading in projects can greatly improve development efficiency and allow us to focus more on business logic implementation.

Introduction to SDWebImage

1. Provides a UIImageView category for loading web images and managing the cache of web images 2. Download network images asynchronously 3. Use Memory + Disk to cache network images asynchronously and automatically manage the cache. Support GIF animation 5. Support WebP format 6. Network pictures of the same URL will not be downloaded repeatedly 7. Invalid urls will not be retried indefinitely 8. Time-consuming operations are in child threads to ensure they do not block the main thread 9. Use GCD and ARC 10. Support Arm64

SDWebImage use

1. Use IImageView+WebCache Category to load cell images in UITableView

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"www.domain.com/path/to/ima..."] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];Copy the code

2. Use Blocks, this scheme can be used to know the download progress of pictures and whether the pictures are loaded successfully or not during the loading process of network pictures

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"www.domain.com/path/to/ima..."] placeholderImage:[UIImage imageNamed:@"placeholder.png"] completed:^(UIImage image, NSError error, SDImageCacheType cacheType, NSURL *imageURL) { ... completion code here ... }];Copy the code

3. Use SDWebImageManager, SDWebImageManager UIImageView + WebCache category the implementation of the interface.

SDWebImageManager manager = [SDWebImageManager sharedManager] ;

[manager downloadImageWithURL:imageURL options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { // progression tracking code } completed:^(UIImage
image, NSError error, SDImageCacheType cacheType, BOOL finished, NSURL imageURL) { if (image) { // do something with image } }];Copy the code

4. There are also SDWebImageDownloader and SDImageCache methods for loading images, but that is not often used. Basically, the above three methods can meet the needs.

SDWebImage process




UIImageView image loading process

SDWebImage interface

SDWebImage is a mature and relatively large framework, but it does not need too many interfaces in the process of use, which is a reflection of the degree of code encapsulation. Here are some commonly used interfaces.

  1. SDWebImage provides multiple interfaces for setting images to UIImageView. Eventually all interfaces will call the interface shown below, which is how most frameworks do it.




    Set the image interface for the UIImageView

  2. To obtain the disk cache size of SDWebImage, sometimes it is necessary to calculate the disk cache size of the application in the project, so the cache size of the image is achieved by using this interface

    [SDImageCache sharedImageCache] getSize];Copy the code
  3. Clear the memory cache, clear the image resources cached in the memory, release the memory resources.

    [[SDImageCache sharedImageCache] clearMemory];Copy the code
  4. With clearing the memory cache, there is also a natural interface for clearing the disk cache

    [[SDImageCache sharedImageCache] clearDisk];Copy the code

SDWebImage parsing

The analysis mainly focuses on the image loading process of SDWebImage, and introduces some processing methods and design ideas in the image loading process of SDWebImage framework.

  1. Set up the image for UIImageView, and then SDWebImage calls this final image loading method.




    1 Set the image for the UIImageView

  2. Cancel the previous image download operation on the corresponding UIImageView before loading the image. Imagine, if we set up a new image for UIImageView, do we care which image the UIImageView was originally loaded with? Should be don’t care! Should we try unloading images from UIImageView?

     [self sd_cancelCurrentImageLoad]Copy the code





    Cancel the previous image download operation of the corresponding UIImageView

The method goes through a loop and finally calls the following method. The framework puts the image’s corresponding download operation into a custom dictionary property of UIView (operationDictionary). The first step is to retrieve all download operations from the UIView’s custom dictionary property (operationDictionary), then call the cancel method in turn, and finally remove the canceled operation from the dictionary property (operationDictionary).




The final undownload method

3. After removing the previously useless image download operation, create a new image download operation and set it to a custom operationDictionary property of UIView.




Create a new image download operation

4. To see how to create a new image download operation, the framework keeps a list of invalid urls. If a URL is invalid, it will be added to this list.




4 image download operation

Generate a unique Key based on the given URL, and then use this Key to find the corresponding image cache.




Find the image cache

5. Read the image cache from the memory based on the key. If the image cache does not match the memory cache, the image cache is read from the disk cache. If none of them hit the cache, the image is downloaded in the doneBlock execution.




5 Read the image cache

6. After the image is downloaded, data corresponding to the image is called back through completed Block




6 picture download operation

In the image download method, a method is called to add various Block callbacks during the creation and download process.




Image download method

Add a state callback Block for the URL loading process




State callback Block

If the URL is being loaded for the first time, the createCallback callback Block is executed, and then the network request starts building in the createCallback, performing various progress Block callbacks during the download.




Build network request

7. When the image is downloaded, it will return to the done Block callback for image conversion and cache operation




7. Image conversion and cache operation

Go back to the UIImageView set image method Block callback and set the corresponding UIImageView image.




Block sets the image

conclusion

SDWebImage, as an excellent image loading framework, provides user methods and interfaces that are very friendly to developers. The internal implementation mostly uses blocks to implement callbacks, and the code may not be intuitive to read. This article aims to explain the general picture loading process of SDWebImage framework to everyone, but the specific details cannot be studied in detail due to the limited space. My ability is limited, there are inevitably mistakes in the article, if you find unreasonable or wrong places in the process of reading, please point out in the comments, I will be the first time to correct, very grateful.

If this article has played a role for you, please click a “like” below, let me know that this article played its role, but also for my hard code word encouragement, ha ha!