SDWebImage
A library that provides a taxonomy for UIImageView to support remote server image loading.
Features:
1. A UIImageView classification that adds web image loading and cache management 2. An asynchronous picture downloader 3 7, ensure that the same image URL will not be downloaded multiple times 8, ensure that forged image URL will not be downloaded repeatedly 9, ensure that the main thread will not blockCopy the code
The working process
1, entrance setImageWithURL: placeholderImage: options: first, according to the placeholderImage then SDWebImageManager according to URL starts processing images. 2, enter SDWebImageManager - downloadWithURL: delegate: options: the userInfo:, To SDImageCache download cache lookup images are from queryDiskCacheForKey: delegate: the userInfo: 3, 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. 4, SDWebImageManagerDelegate callback webImageManager: didFinishWithImage: to UIImageView + WebCache front-end display pictures, etc. 5. If the image is not in the memory cache, NSInvocationOperation is generated and added to the queue to find whether the image has been cached from the disk. 6, according to the URLKey in the disk cache directory try to read the picture file. This step is performed in NSOperation, so the result callback to the main thread is notifyDelegate:. 7. If the previous operation read the image from the hard disk, add the image to the memory cache (if the free memory is too small, the memory cache will be emptied first). SDImageCacheDelegate callback imageCache: didFindImage: forKey: the userInfo:. Then call back to the display image. 8, 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:. 9. Share or rebuild a download SDWebImageDownloader to start downloading images. 10, image download by NSURLConnection to do, implement the relevant delegate to determine the image download, download complete and download failure. 11, 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. 12. 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. 13, in the main thread notifyDelegateOnMainThreadWithInfo: declare decoding, imageDecoder: didFinishDecodingImage: the userInfo: Callback to SDWebImageDownloader. ImageDownloader: didFinishWithImage: callback told SDWebImageManager image download is complete. Notify all downloadDelegates to download 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. 15. SDImageCache registers some message notifications during initialization, clears memory image cache during memory warning or backtracking, and clears expired images at the end of application. SDWI also provides UIButton+WebCache and MKAnnotationView+WebCache for easy use. 17. SDWebImagePrefetcher can download images in advance for subsequent use.Copy the code
Source code analysis
The main object used
First, picture download
1、 SDWebImageDownloader
-
1. Singleton, picture downloader, responsible for asynchronous picture downloading, and optimized image loading
-
2. The image download is placed in an NSOperationQueue with a default maximum of 6 concurrent operations
-
3. Each image corresponds to some callbacks (download progress, complete callback, etc.). The callback information will be stored in the URLCallbacks of the downloader (a dictionary, key is url, value is image download callback array). So the downloader places the download task in a barrierQueue and sets a barrier to ensure that only one thread accesses the URLCallbacks at a time. An NSOperation is created in the block that creates the URLCallbacks and added to the NSOperationQueue.
-
4. Each image download is an Operation class, which is added to a queue after creation. SDWebimage defines a protocol SDWebImageOperation as the basic protocol for image download operations and declares a cancel method to cancel the operation. @protocol SDWebImageOperation -(void)cancel; @end
-
5. To download images, SDWebImageDownloaderOperation depend entirely on the NSURLConnection class, inheritance, and realized NSURLConnectionDataDelegate agreement method
connection:didReceiveResponse: connection:didReceiveData: connectionDidFinishLoading: connection:didFailWithError: connection:willCacheResponse: connectionShouldUseCredentialStorage: – the connection: willSendRequestForAuthenticationChalleng – the connection: didReceiveData: method, receive data, create a CGImageSourceRef object, In the first time to obtain data (image width, height), before the image is downloaded, create an image object with CGImageSourceRef object, and generate a UIImage object for callback after scaling and decompression, as well as download progress processing. Note: Zoom: SDScaledImageForKey function in SDWebImageCompat unzip: SDWebImageDecoder file decodedImageWithImage
2, SDWebImageDownloaderOption
- 1. Inherits from NSOperation class, does not simply implement the main method, but uses the more flexible start method, in order to manage their own download status
- 2. The start method creates the NSURLConnections object for the download, starts the download of the image, and throws a notification of the start of the download.
- 3. Summary: The core of download is to use NSURLSession to load data. Each image download has an operation operation to complete, and these operations are put into an operation queue, so that concurrent download of images can be realized.
3. SDWebImageDecoder (asynchronous decoding of pictures)
Second, the cache
Reduces network traffic. After downloading an image, you can save it to the local PC. When you download another image, you can directly obtain it from the local PC, which improves user experience.
SDWebImage provides image caching, mainly done by SDImageCache. This class handles the memory cache as well as an optional disk cache, where writes to the disk cache are asynchronous and do not affect the UI.
1. Memory cache and disk cache
- 1. The processing of memory cache is realized by NSCache object. NSCache is similar to a collection container, which stores key-value pairs, similar to nsDictionary class. At the same time, these objects are not important to the program and will be released automatically if memory is tight.
- 2. The processing of disk cache using NSFileManager object, image storage location in the cache folder, in addition to SDImageCache also defines a serial queue to asynchronously store images.
- 3.SDImageCache provides a number of methods to cache, get, remove, and empty images. In memory, we use this key as the key of the NSCache. On disk, we use this key as the file name of the image. The URL of a remote downloaded image is the best choice for this key.
2. Store images
The disk cache operation is processed as a task in a serial queue, the image format is checked as JPEG or PNG, the image data is converted to the response, and the data is written to disk (the file name is the MD5 string for the key value).
3, query pictures
Memory and disk query picture API:
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
Copy the code
To check whether the image specified by key exists locally, use the following API:
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
Copy the code
4. Remove the image
Remove image API:
- (void)removeImageForKey:(NSString *)key;
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
Copy the code
5. Clean up pictures (disk)
Clear disk images can be completely empty or partially empty, completely empty is the cache folder delete.
- (void)clearDisk;
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
Copy the code
Partial cleanup removes files based on the parameters set: the cache validity period of the file (maxCacheAge: 1 week by default) and the maximum cache size (maxCacheSize: If all the file size is greater than the maximum value, you will be in accordance with the reverse order of file was last modified time, to each half of the recursion remove what files, early know cache file total size is less than the maximum), specific code reference – (void) cleanDiskWithCompletionBlock;
6, summary
SDImageCache processing provides the above API, also provides the cache size, the number of images in the cache API, etc.
Common interfaces and attributes:
(1) -getSize: obtain the disk cache size (2) -getDiskCount: obtain the disk cache number of images (3) -clearMemory: Remove all memory images (4) - removeImageForKey:(NSString *) Key series methods: remove images from memory or hard disk as specified on request (5) maxMemoryCost: Sum of pixels held in memory (6) maxCacheSize: Maximum cache size is in bytes. There is no default setting, which is 0, and the prerequisite for cleaning the disk cache is self.maxCacheSize > 0, so 0 means unlimited. (7) maxCacheAge: The maximum time to be retained in memory is in seconds. The default value is one weekCopy the code
Third, SDWebImageManager
In actual use, SDWebImageDownloader and SDImageCache classes are not directly used to download and store images, but use SDWebImageManager to manage. Including the usual use of UIImageView+WebCache control classification, are using SDWebImageManager to handle, the object internal definition of a picture downloader (SDWebImageDownloader) and picture cache (SDImageCache)
@interface SDWebImageManager : NSObject @property (weak, nonatomic) id <SDWebImageManagerDelegate> delegate; @property (strong, nonatomic, readonly) SDImageCache *imageCache; @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; . @endCopy the code
The SDWebImageManager declares a delegate property, which is actually an ID object, and the proxy declares two methods
// Control if the image is not found in the cache, Should download which image - (BOOL) imageManager: (SDWebImageManager *) imageManager shouldDownloadImageForURL (imageURL NSURL *); (UIImage *)imageManager:(SDWebImageManager *)imageManager:(UIImage *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL;Copy the code
These two methods will be SDWebImageManager – downloadImageWithURL: options: progress: completed: method calls, and this method is the core of the SDWebImageManager class (specific see the source code)
SDWebImageManager API:
(1) - (void)cancelAll: cancels all operations in runningOperations (2) - (BOOL)isRunning: Check for running operation, in this case, the operation is to download and cache of combination operation (3) - downloadImageWithURL: options: progress: completed: Core method (4) - (BOOL)diskImageExistsForURL:(NSURL *) URL: Specifies whether the image of the URL is cached on diskCopy the code
View extension
When we use SDWebImage, the most used extension is UIImageView+WebCache for UIImageView, Core method is sd_setImageWithURL: placeholderImage: options: progress: completed:, its use SDWebImageManager singleton download and cache images.
In addition to extending UIImageView, SDWebImage also extends UIView, UIButton, MKAnnotationView and other view classes. For details, please refer to the source code. In addition to using the extension method to download images, Images can also be downloaded using the SDWebImageManager.
UIView + WebCacheOperation classification:
The image action object corresponding to the current view is stored (via runtime properties) in the base class
Stored structure: a loadOperationKey property, value is a dictionary (dictionary structure: key: UIImageViewAnimationImages or UIImageViewImageLoad, the value is operation array (dynamic) or objects)
UIButton + WebCache classification
According to the different state of the button, the downloaded picture will be set according to the different state
imageURLStorageKey:{state:url}
Five, technical points
- 1. The dispatch_barrier_sync function is used to set the sequence of operations and ensure that subsequent operations are performed after tasks are completed. Often used to ensure thread-safety operations
- 2.NSMutableURLRequest: Used to create a network request object. You can configure the request header and other information as required
- 3. The NSOperation and NSOperationQueue: Operation queue is a kind of warning OC concurrent processing method, based on the GCD, relative to the GCD, operation queue has the advantage that you can cancel the task in the task processing queue management in the preparation of dependency on easier, we see how to use dependency in the SDWebImage will download sequence set to last in, first out of order
- 4.NSURLSession: used for network request and corresponding processing
- 5. Start background tasks
- 6.NSCache class: a collection-like container that stores key-value pairs. Similar to the NSDictionary class, we often use caching to temporarily store short-lived but expensive objects. Reusing these objects optimizes performance because their values do not need to be recalculated. On the other hand, these objects are not critical to the program and are discarded when memory is tight
- 7. Policies for clearing cached images: in particular, setting the maximum cache size. If the total size of all cached files exceeds this size, the premature files are removed recursively half at a time, in reverse order of the last modification time of the files, until the actual size of the cache is less than the maximum size we set.
- 8. Image decompression operation: this operation can be seen in SDWebImageDecoder. M +decodedImageWithImage method implementation.
- 9. Processing of GIF images
- 10. Processing of WebP pictures.
More: iOS Interview Questions