Introduction to the

SDWebImage provides a simple API for obtaining remote URL images; In normal development, the most frequently used scenario is the requirement of displaying remote pictures in the cell in the list. In the specific implementation, interface lag caused by loading pictures should be avoided, list lag and other phenomena should be avoided. Therefore, the following functions need to be coded:

  • Use the placeholder picture to display the UI interface, and refresh the control after the asynchronous thread loads the picture successfully
  • Cache mechanism, downloaded pictures to do memory cache and disk cache
  • Remove cached content when app memory is running low

Frame structure of SDWebImage

SDWebImage image download classification, as long as a line of code can achieve asynchronous image download and cache functions.

Function introduction

  1. A UIImageView class that adds web image loading and cache management
  2. An asynchronous picture loader
  3. An asynchronous memory plus disk integration stores images and automatically processes expired images
  4. Supports dynamic GIFs
    • Before 4.0, giFs didn’t look very good
    • After 4.0, giFs are loaded based on FLAnimatedImage
  5. Support webP images
  6. Background image decompression processing
  7. Make sure the same image URL is not downloaded multiple times
  8. Make sure forged image urls do not try to download again
  9. Make sure the main thread is not blocked

Realize the principle of

  1. Architecture Diagram (UML class Diagram)

  1. Flowchart (method invocation sequence diagram)

The directory structure

  • A. SDWebImageDownloader Downloader SDWebImageDownloaderOperation

  • A. SDImageCache Cache

  • Utils

    ○ SDWebImageManager

    ○ SDWebImageDecoder

    ○ SDWebImagePrefetcher

  • Categories

    ○ UIView+WebCacheOperation

    ○ UIImageView+WebCache

    ○ UIImageView+HighlightedWebCache

    ○ UIButton+WebCache

    ○ MKAnnotationView+WebCache

    ○ NSData+ImageContentType

    ○ UIImage+GIF

    ○ UIImage+MultiFormat

    ○ UIImage+WebP

  • Other ○ SDWebImageOperation (protocol) ○ SDWebImageCompat (macro definition, constant, and universal function)

Related class name and function description

SDWebImageDownloader: SDWebImageDownloader is used to download images and optimize image loading

SDWebImageDownloaderOperation: inheritance in NSOperation, used to download tasks

SDImageCache: Used to handle memory caching and (optional) disk caching, where disk caching is asynchronous and therefore does not block the main thread

SDWebImageManager: as the silent giver behind UIImageView+WebCache, its main function is to combine image download (SDWebImageDownloader) and image cache (SDImageCache) two independent functions

SDWebImageDecoder: Image decoder, used to decode images after downloading

SDWebImagePrefetcher: pre-download images, convenient for subsequent use, image download priority is low, its internal by

SDWebImageManager: to handle image downloading and caching

UIView+WebCacheOperation: It is used to record the image loading operation, which can be canceled or removed if necessary

UIImageView+WebCache: integrated SDWebImageManager image download and cache functions into UIImageView methods, convenient for the simple use of the caller

UIImageView+HighlightedWebCache: similar to UIImageView+WebCache, is also packed with SDWebImageManager, but is used to load the image in highlighted state

UIButton+WebCache: similar to UIImageView+WebCache, integrated SDWebImageManager image download and cache functions to UIButton methods, convenient for the simple use of the caller

MKAnnotationView+WebCache: similar to UIImageView+WebCache

NSData+ImageContentType: Format used to retrieve image data (JPEG, PNG, etc.)

UIImage+GIF: used to load GIFs

UIImage+MultiFormat: Converts binary data in different formats to UIImage objects

UIImage+WebP is used to decode and load WebP images

The working process

  • Entrance setImageWithURL: placeholderImage: options: first, according to the placeholderImage then SDWebImageManager according to URL starts processing images.

  • Enter SDWebImageManager – downloadWithURL: delegate: options: the userInfo: to SDImageCache from cache lookup picture is already downloaded QueryDiskCacheForKey: delegate: the userInfo:.

  • The first images from memory cache to find if there is a picture, if have image cache in memory, SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo: to SDWebImageManager.

  • SDWebImageManagerDelegate callback webImageManager: didFinishWithImage: to UIImageView + WebCache front-end display pictures, etc.

  • If not in the memory cache, NSInvocationOperation is generated and added to the queue to start looking from the hard disk to see if the image has been cached.

  • Try to read the image file in the disk cache directory according to URLKey. This step is performed in NSOperation, so the result callback to the main thread is notifyDelegate:.

  • If the image is read from the hard disk, it is added to the memory cache (if the free memory is too small, the memory cache is emptied first). SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo: then the callback display pictures.

  • If you do not read from the hard disk cache directory images, point out the picture does not exist in all cache, need to download the pictures, the callback imageCache: didNotFindImageForKey: the userInfo:.

  • Share or rebuild a downloader called SDWebImageDownloader to start downloading images.

  • Image download by NSURLConnection(NSURLSession used after 3.8.0), implement the related delegate to determine the image download, download completion and download failure.

  • In the connection: didReceiveData: use ImageIO made according to the pictures download progress load effect. After completion of the connectionDidFinishLoading: data download to SDWebImageDecoder do image decoding process.

  • Image decoding is done in an NSOperationQueue without slowing down the main thread UI. If there is a need to download images for secondary processing, it is best to do it here, much more efficient.

  • Completed in the main thread notifyDelegateOnMainThreadWithInfo: declaration of decoding, imageDecoder: didFinishDecodingImage: the userInfo: give SDWebImageDownloader callback.

  • ImageDownloader: didFinishWithImage: callback told SDWebImageManager image download is complete.

  • Notify all downloadDelegates that the download is complete, call-back to display the image where it is needed.

  • Save the image to SDImageCache, memory cache and hard disk cache at the same time. Writing files to hard disk is also done as a separate NSInvocationOperation to avoid slowing down the main thread.

  • SDImageCache registers some message notifications during initialization, clears the memory image cache during memory warnings or backlogs, and clears expired images at the end of the application.

  • SDWebImagePrefetcher can download images in advance for later use.

Frequently seen exam

  1. How long is the image file cached: 1 week

_maxCacheAge = kDefaultCacheMaxCacheAge

  1. How is the memory cache of SDWebImage implemented?

NSCache

  1. What is the maximum number of concurrent requests for SDWebImage?

MaxConcurrentDownloads = 6

  • Is the program fixed dead, can be adjusted through the properties!
  1. Does SDWebImage support GIFs? GIF
1. #import <ImageIO/ImageIO.h>
2. [UIImage animatedImageWithImages:images duration:duration];
Copy the code
  1. How does SDWebImage differentiate between images in different formats

    • Judging by the first byte of image data!
    • PNG: higher compression than JPG, but lossless compression, high decompression performance, Apple recommended image format!
    • JPG: the highest compression ratio of a picture format, lossy compression! Most used scene, camera! Decompression performance is not good!
    • GIF: sequence frame GIF, features: only support 256 colors! The most popular time is 1998 ~ 1999, have patent!

6. How to determine the name of SDWebImage cache?

  • md5

  • If you simply use the file name to save, the probability of the same name is very high!

  • Use the MD5 hash function! Md5 the full URL and the result is a string of 32 characters!

  1. How SDWebImage memory warnings are handled!
    • Use the notification center to observe
    • - UIApplicationDidReceiveMemoryWarningNotificationA memory warning notification was received
    • performclearMemoryMethod, clear the memory cache!
    • - UIApplicationWillTerminateNotificationReceived notification that the application is about to terminate
    • performcleanDiskMethod, clean up the disk cache!
    • - UIApplicationDidEnterBackgroundNotificationBackground notification of application entry is received
    • performbackgroundCleanDiskMethod, background clean disk!
    • Through the above notification listening, you can ensure that the size of the cache file is always under control!
    • clearDiskClear the disk cache, all the files in the cache directory, all delete!

To actually work, delete the cache directory directly and create an empty directory with the same name again!

Green mountains do not change, green water flow, see you soon, thank every beautiful woman for her support!