Simple use of SDWebImage and sdwebimage

Source: Internet
Author: User

Simple use of SDWebImage and sdwebimage

I. Preface

The first time I used SDWebImage, I used it as my rehabilitation doctor. Remember that there was a table to show all user portraits. When you do not use it, the table will be stuck every time you load it. Later, you will find that the table will not be stuck. In an instant, I feel love in this world.

Ii. Installation

First, the git address of SDWebImage is https://github.com/rs/sdwebimage. We can download it directly here and add it to our project.

3. Use Cases (provided that the library SDWebImage has been imported)

1. Scenario 1. Attach Images

You can use SDWebImage to load remote images and cache images. The next request will check whether the images already exist in the cache. If yes, you can directly obtain the local cache, if not, request again. It is easy to use. You can import data to classes that require this scenario.

#import "UIImageView+WebCache.h"

Then call:

- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

You can.

We can also see other methods in UIImageView + WebCache. h, which is similar to the above method. You can view them on your own.

2. Scenario 2: Use it for local cache

Most of the time, we may take a photo to get an image that needs to be used in multiple places, so we want to put this image in the cache, then, each time you use this image, you can retrieve it in a specific way. SDWebImage has such a class: SDImageCache. This class perfectly helped us solve this problem.

When using this function, we first need to import the data in the class we use:

#import "SDImageCache.h"

Then you can perform related operations. Let's take a look at the SDImageCache. h file:

@property (assign, nonatomic) NSUInteger maxMemoryCost;/** * The maximum length of time to keep an image in the cache, in seconds */@property (assign, nonatomic) NSInteger maxCacheAge;/** * The maximum size of the cache, in bytes. */@property (assign, nonatomic) NSUInteger maxCacheSize;/** * Returns global shared cache instance * * @return SDImageCache global instance */+ (SDImageCache *)sharedImageCache;/** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */- (id)initWithNamespace:(NSString *)ns;/** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */- (void)addReadOnlyCachePath:(NSString *)path;/** * Store an image into memory and disk cache at the given key. * * @param image The image to store * @param key   The unique image cache key, usually it's image absolute URL */- (void)storeImage:(UIImage *)image forKey:(NSString *)key;/** * Store an image into memory and optionally disk cache at the given key. * * @param image  The image to store * @param key    The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;/** * Store an image into memory and optionally disk cache at the given key. * * @param image       The image to store * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage * @param imageData   The image data as returned by the server, this representation will be used for disk storage *                    instead of converting the given image object into a storable/compressed image format in order *                    to save quality and CPU * @param key         The unique image cache key, usually it's image absolute URL * @param toDisk      Store the image to disk cache if YES */- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;/** * Query the disk cache asynchronously. * * @param key The unique key used to store the wanted image */- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;/** * Query the memory cache synchronously. * * @param key The unique key used to store the wanted image */- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;/** * Query the disk cache synchronously after checking the memory cache. * * @param key The unique key used to store the wanted image */- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;/** * Remove the image from memory and disk cache synchronously * * @param key The unique image cache key */- (void)removeImageForKey:(NSString *)key;/** * Remove the image from memory and disk cache synchronously * * @param key             The unique image cache key * @param completionBlock An block that should be executed after the image has been removed (optional) */- (void)removeImageForKey:(NSString *)key withCompletition:(void (^)())completion;/** * Remove the image from memory and optionally disk cache synchronously * * @param key      The unique image cache key * @param fromDisk Also remove cache entry from disk if YES */- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;/** * Remove the image from memory and optionally disk cache synchronously * * @param key             The unique image cache key * @param fromDisk        Also remove cache entry from disk if YES * @param completionBlock An block that should be executed after the image has been removed (optional) */- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletition:(void (^)())completion;/** * Clear all memory cached images */- (void)clearMemory;/** * Clear all disk cached images. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */- (void)clearDiskOnCompletion:(void (^)())completion;/** * Clear all disk cached images * @see clearDiskOnCompletion: */- (void)clearDisk;/** * Remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock;/** * Remove all expired cached image from disk * @see cleanDiskWithCompletionBlock: */- (void)cleanDisk;/** * Get the size used by the disk cache */- (NSUInteger)getSize;/** * Get the number of images in the disk cache */- (NSUInteger)getDiskCount;/** * Asynchronously calculate the disk cache's size. */- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock;/** * Check if image exists in cache already */- (BOOL)diskImageExistsWithKey:(NSString *)key;/** *  Get the cache path for a certain key (needs the cache path root folder) * *  @param key  the key (can be obtained from url using cacheKeyForURL) *  @param path the cach path root folder * *  @return the cache path */- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;/** *  Get the default cache path for a certain key * *  @param key the key (can be obtained from url using cacheKeyForURL) * *  @return the default cache path */- (NSString *)defaultCachePathForKey:(NSString *)key;

Don't look at it. Let's take a look.

Save image:

 SDImageCache *imageCache = [SDImageCache sharedImageCache];

[ImageCache storeImage: image forKey: @ "myphoto" toDisk: YES];

Image Retrieval:

 SDImageCache *imageCache = [SDImageCache sharedImageCache];    UIImage *image = [imageCache imageFromDiskCacheForKey:@"myphoto"];

In this way, you can get your saved images. Let's take a look at the SDImageCache. h class, which provides methods for saving images to memory and disks, as well as image retrieval methods, and methods for determining whether the image exists. You can also delete images, clear the disk cache, and obtain the cache size.

Scenario 3: Clear cache in settings

Simply put, when we click the clear cache button, the following message is triggered:

-(Void) Prepare aches {[MBProgressHUD showMessage: @ "cleaning .. "]; [[SDImageCache includimagecache] clearMemory]; [[SDImageCache includimagecache] clearDisk]; [self operated: @ selector (cleanCacheSuccess) withObject: nil waitUntilDone: YES];}

-(Void) cleanCacheSuccess

 

{

 

Dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) 2 * NSEC_PER_SEC), dispatch_get_main_queue (), ^ {

 
 

Self. cachelab. text = @ "0.00 M ";

 

Return;

});

 

}

It is easy to clear all the images cached by SDWebImage, including the cached images in the memory and the cached images on the disk.

 

There are other application scenarios, so I will not go into details here.

IV. Implementation Principle

In fact, the key to the principle that SDWebImage can implement caching is the key value.

For example, we are using

- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

In fact, the url is used as the key value of an image, and then the corresponding image is stored. If the url requested next time is the same as the url of this request, the image will be taken directly based on the url (this key). If the image cache of the url as the key does not exist, request the remote server and then match the url with the image again, and then store it.

V. Others

To be continued.

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.