Interpretation of IOS image loading framework sdwebimage

Time:2021-10-9

objective

When using sdwebimage to load pictures, especially when loading GIF and other large pictures, sdwebimage will cache the pictures in memory, which is very memory consuming. At this time, we need to release the memory cache of sdwebimage at an appropriate time so as not to cause app flash back.

SDWebImage It provides the image download classification of uiimageview, uibutton and mkannotationview. As long as one line of code, it can realize the image asynchronous download and caching function.

In this way, developers do not need to spend too much energy on the details of image download and concentrate on the business logic.

Sdwebimage features

  1. It provides the classification of uiimageview, uibutton and mkannotationview, which are used to display network pictures and cache management
  2. Asynchronously downloading pictures
  3. Asynchronous cache (memory + disk), and automatically manage cache validity
  4. Background image decompression
  5. The same URL will not be downloaded repeatedly
  6. Automatically identify invalid URLs and won’t try again and again
  7. Do not block the main thread
  8. High performance
  9. Using GCD and arc
  10. Support multiple picture formats (including webp format)
  11. Support dynamic graph (GIF)
  12. The moving picture effect before 4.0 is not very good
  13. After 4.0 based onFLAnimatedImageLoading dynamic diagram

Note: the code selected in this article is version 3.7.3, so the dynamic graph loading does not support flanimatedimage.

Sdwebimage usage

1. Use uiimageview + webcache in uitableview

Copy codeThe code is as follows:
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@”http://www.domain.com/path/to/image.jpg“] placeholderImage:[UIImage imageNamed:@”placeholder.png”]];

2. Use callback blocks

Get the callback of picture download progress and picture loading completion (download completion or read cache) in the block. If you cancel the request operation before the picture loading is completed, you will not receive a successful or failed callback


[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"https://imgs.developpaper.com/imgs/image.jpg"]
           placeholderImage:[UIImage imageNamed:@"placeholder.png"]
               completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                 ... completion code here ...
               }];

3. Use of sdwebimagemanager

The core of uiimageview (webcache) classification is the download and cache processing of sdwebimagemanager, which combines picture download and picture cache. The SD web image manager can also be used alone.


SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager loadImageWithURL: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
            }
          }];

4. Use sdwebimagedownloader alone to download pictures asynchronously

We can also use sdwebimagedownloader alone to download images, but the image content will not be cached.


SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
[downloader downloadImageWithURL:imageURL
               options:0
              progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                // progression tracking code
              }
              completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                if (image && finished) {
                  // do something with image
                }
              }];

5. Use sdimagecache alone to asynchronously cache pictures

Sdimagecache supports memory cache and asynchronous disk cache (optional). If you want to use sdimagecache alone to cache data, you can use singleton or create an sdimagecache instance with independent namespace.

How to add a cache:


[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];

By default, image data will be cached in both memory and disk. If you want to cache only in memory, you can use the following method:


[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey toDisk:NO];

When reading the cache, you can use the querydiskcacheforkey: done: method. The key of the image cache is unique, usually the absolute URL of the image.


SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image) {
    // image is not nil if image was found
  }];

6. User defined cache key

Sometimes, part of the URL of an image may change dynamically (such as restrictions on access), so we only need to use the unchanged part of the URL as the key for caching.


SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) {
      url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
      return [url absoluteString];
    };

common problem

Question 1:When using ImageView in uitableviewcell to load network pictures of different sizes, there will be a size scaling problem.

Solution:

Customize the uitableviewcell, override the – layoutsubviews method, and adjust the position and size;

Or directly discard the ImageView of uitableviewcell and add an ImageView as a child control.

Question 2:Picture refresh problem: sdwebimage ignores the caching control settings returned by all servers during caching, and there is no time limit during caching, which means that the picture URL must be static, and the picture content corresponding to a URL on the server is not allowed to be updated. But what if the server storing the picture is not controlled by itself, that is, the picture content is updated, but the URL is not updated?

Solution: after calling SD_ Setimagewithurl: placeholderimage: options: when using the method, set the options parameter to sdwebimagerefreshcached. Although this will reduce performance, the caching control returned by the server will be taken into account when downloading images.

Question 3:How to add a default progress indicator when loading a picture?

Solution: after calling – SD_ Before the setimagewithurl: method, call the following method:


 [imageView sd_setShowActivityIndicatorView:YES];
 [imageView sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];
```![](https://imgs.developpaper.com/imgs/2829694-48307b4d71bc5800.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/300)

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]