iOS downloads cache with Sdwebimage pictures

Source: Internet
Author: User
Tags ssl certificate

First, let's look at the use of Sdwebimage:

1, import the framework, the introduction of the header file:

#import "Uiimageview+webcache.h"

You can also use cocoapods directly to introduce and manage

(OC as follows)

Platform:ios, ' 7.0 '

Pod ' sdwebimage ', ' ~>3.8 '

(Swift) and make sure to add the Use_frameworks,ios version to 8.0 +

Platform:ios, ' 8.0 '

use_frameworks!

2. Image download and caching method:

Get the URL of the current picture

-(Nsurl *) Sd_imageurl;

Asynchronously downloads a picture and caches it

-(void) Sd_setimagewithurl: (nsurl *) URL;

Asynchronously downloads the picture and caches it, displays the placeholder image before downloading, and then replaces it after downloading.

-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder;

/**

* Asynchronously download picture and cache

* @param url Download picture path

* @param placeholder placeholder image until download is complete

* @param options Download Image selection method (this option is the options to be described in 3)

*/

-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder options: (sdwebimageoptions) options;

/**

* Download images asynchronously and cache, but no placeholder picture, you can do things in block after completion

* @param url Download image URL

* @param completedblock

Sdwebimagecompletionblock: (UIImage *image, Nserror *error, Sdimagecachetype cachetype, Nsurl *imageurl)

Block can be downloaded images, error messages, cache type, download image address parameters, to the user to do the appropriate action

*/

-(void) Sd_setimagewithurl: (nsurl *) URL completed: (sdwebimagecompletionblock) Completedblock;

/**

* Asynchronously download picture and cache, provide placeholder picture, and can do things in block after completion

* @param url Download image URL

* @param placeholder placeholder image until download is complete

* @param completedblock

Sdwebimagecompletionblock:uiimage *image, Nserror *error, Sdimagecachetype cachetype, NSURL *imageURL)

Block can be downloaded images, error messages, cache type, download image address parameters, to the user to do the appropriate action

*/

-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder completed: ( Sdwebimagecompletionblock) Completedblock;

/**

* Asynchronously download the picture and cache, not only provide a bitmap, you can also set the download mode: options, you can do things in block after completion

* @param url Download picture path

* @param placeholder placeholder image until download is complete

* @param options Download Image selection method

* @param completedblock Ibid.

*/

-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder options: (sdwebimageoptions) options Completed: (sdwebimagecompletionblock) Completedblock;

/**

* Asynchronously download the picture and cache, not only provide a bitmap, you can also set the download mode: options, while listening to the download progress, after the completion of the block can do things

* @param url Download picture path

* @param placeholder placeholder image until download is complete

* @param options Download Image selection method

* @param progress Picture Download progress

* Sdwebimagedownloaderprogressblock:nsinteger receivedsize (current download size), Nsinteger expectedsize (total size)

* @param completedblock Ibid.

*/

-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder options: (sdwebimageoptions) options Progress: (Sdwebimagedownloaderprogressblock) Progressblock completed: (sdwebimagecompletionblock) CompletedBlock;

/**

* Asynchronously download the picture and cache, not only provide the bitmap, you can also set the download mode: options, while listening to the download progress, but also provide the download size, you can do in block after the completion of things

* @param url Download picture path

* @param placeholder placeholder image until download is complete

* @param options Download Image selection method

* @param Progress

* Sdwebimagedownloaderprogressblock:nsinteger receivedsize (current download size), Nsinteger expectedsize (total size)

* @param completedblock Ibid.

*/

-(void) Sd_setimagewithpreviouscachedimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder options: ( Sdwebimageoptions) Options Progress: (Sdwebimagedownloaderprogressblock) Progressblock completed: ( Sdwebimagecompletionblock) Completedblock;

3. Options All option

Retry after failure

sdwebimageretryfailed = 1 << 0,

Lowest priority, automatically pausing some of the internal download operations while UI interaction is in progress

sdwebimagelowpriority = 1 << 1,

Cache memory Only

sdwebimagecachememoryonly = 1 << 2,

Progressive download, the displayed image is progressively in the download

Sdwebimageprogressivedownload = 1 << 3,

Refresh Cache

sdwebimagerefreshcached = 1 << 4,

Background download

Sdwebimagecontinueinbackground = 1 << 5,

/**

* Handles cookies stored in Nshttpcookiestore by setting

* Nsmutableurlrequest.httpshouldhandlecookies = YES;

*/

Sdwebimagehandlecookies = 1 << 6,

Allow an invalid SSL certificate to be used

Sdwebimageallowinvalidsslcertificates = 1 << 7,

High-Priority Downloads

sdwebimagehighpriority = 1 << 8,

Delay placeholder

Sdwebimagedelayplaceholder = 1 << 9,

Change the animated image

Sdwebimagetransformanimatedimage = 1 << 10,

/**

* By default, image was added to the imageView after download. Some cases, we want to

* The hand before setting the image (apply a filter or add it with Cross-fade animation for instance)

* Use this flag if you want to manually set the "image in the" completion when success

*/

Sdwebimageavoidautosetimage = 1 << 11

4, Memory Processing: When the app receives a memory warning, we want to free memory (can be released in the APPDELEGATE.M applicationdidreceivememorywarning method, Can also be released in the controller's Didreceivememorywarning method)

Sdwebimagemanager *manager = [Sdwebimagemanager Sharedmanager];

Cancel the operation being downloaded

[Manager Cancelall];

Clear the memory cache

[Manager.imagecache Clearmemory];

Freeing the disk's cache

[Manager.imagecache Cleandisk];

5, using the Sdwebimagemanager class: Can do some asynchronous loading work

Sdwebimagemanager *manager = [Sdwebimagemanager Sharedmanager];

UIImage *cachedimage = [manager Imagewithurl:url]; Load a picture that needs to be cached

if (cachedimage) {

If the cache is hit, use the cached picture to do the operation

} else {

If the cache is not hit, download a picture of the specified network location and give a delegate method

[Manager Downloadwithurl:url Delegate:self];

}

Of course your class wants to implement the Sdwebimagemanagerdelegate protocol, and to implement the webimagemanager:didfinishwithimage of the Protocol: method.

When the download is complete, call the callback method so that the downloaded picture is displayed

-(void) Webimagemanager: (Sdwebimagemanager *) Imagemanager didfinishwithimage: (UIImage *) Image {

}

6. Independent asynchronous image download and independent asynchronous image caching

Stand-alone asynchronous image download

You may use asynchronous image download alone, you must use Downloaderwithurl:delegate: To create a Sdwebimagedownloader instance.

Sdwebimagedownloader *downloader = [Sdwebimagedownloader downloaderwithurl:url delegate:self];

This method of Sdwebimagedownloaderdelegate protocol imagedownloader:didfinishwithimage: The download will start immediately and complete when it is invoked.

Stand-alone asynchronous image caching

The Sdimagecache class provides an instance of creating an empty cache and uses method Imageforkey: To find the current cache.

UIImage *mycachedimage = [Sdimagecache Sharedimagecache] imagefromkey:mycachekey];

Storing an image to the cache is a way to use Storeimage:forkey:

[Sdimagecache Sharedimagecache] Storeimage:myimage Forkey:mycachekey];

By default, images are stored in the memory cache and in the disk cache. If you only want to use StoreImage:forKey:toDisk in the memory cache: the third parameter of the method is replaced with a negative value.

To replace.

Second, sdwebimage internal realization principle

How does Sdimagecache do data management? (as shown in:)


Picture explanation: The memory plane is quite a buffer, storing the picture in the form of Key-value. All cached images are cleared when there is not enough memory. In the way of searching the file system to do management, the file replacement method is in time, the rejection time is more than a week of picture files. When Sdwebimagemanager to Sdimagecache to the resources, first search the memory plane of the data, if there is a direct return, there is no way to access the disk, the picture is read from the disk, and then do the decoder, put the picture object to the memory plane to do the backup, and then return to the call layer.

1, entrance setImageWithURL:placeholderImage:options: Will placeholderimage display first, and then Sdwebimagemanager based on the URL to start processing pictures.

2, enter Sdwebimagemanager-downloadwithurl:delegate:options:userinfo:, to Sdimagecache from the cache to find whether the picture has been downloaded QueryDiskCacheForKey:delegate:userInfo:.

3, if there is already a picture cache in memory, Sdimagecachedelegate callback ImageCache:didFindImage:forKey:userInfo: to Sdwebimagemanager.

4, Sdwebimagemanagerdelegate callback Webimagemanager:didfinishwithimage: to Uiimageview+webcache and other front-end display pictures.

5. If not in the memory cache, the build nsinvocationoperation is added to the queue to start looking for pictures from the hard disk if it is already cached.

6, according to Urlkey in the hard disk cache directory to try to read the picture file. This step is performed at Nsoperation, so the callback notifydelegate is returned to the main thread:.

7. If there is a picture in the hard disk, add the picture to the memory cache (if the free memory is too small, the memory cache will be emptied first). Sdimagecachedelegate callback ImageCache:didFindImage:forKey:userInfo:. And then callback the display image.

8, if from the hard disk cache directory can not read the picture, that all the cache does not exist the picture, need to download the picture, callback ImageCache:didNotFindImageForKey:userInfo:.

9. Share or regenerate a downloader sdwebimagedownloader start downloading pictures.

10, image download by nsurlconnection to do, to achieve relevant delegate to determine the picture download, download complete and download failed.

11, Imagedownloader:didfinishwithimage: Callback to Sdwebimagemanager tell the picture download completed.

12, notify all the Downloaddelegates download complete, callback to the place to display pictures.

13, save the picture to Sdimagecache, the memory cache and the hard disk cache are saved simultaneously. Writing files to the hard disk is also done in a separate nsinvocationoperation to avoid slowing down the main thread. Sdimagecache registers some message notifications at initialization time, cleans up the memory image cache when the memory is warning or back to the background, and cleans up outdated images when the app is finished.

The general process sums up a bit like this:

Sd_webimage mainly Sd_webimagemanager a singleton class to manage the two singleton classes Sd_webimagedownloader and Sd_imagecache.
1. When performing the download operation, Sd_imagecache will look for this image from the memory image cache, and if so, sd_imagecachedelegate will display the image through a series of callbacks to Uiimageview+webcache to the front. If the memory cache is not
2. Will be found in the hard disk cache, if there is, the picture will be added to the memory cache (note here, if the free memory is too small, the memory cache will be emptied first) and then also sd_imagecachedelegate through a series of callbacks to uiimageview+ Webcache to the front-end display picture;
3. You need to use Sd_webimagedownloader to start downloading pictures, image download by nsurlconnection to do, to achieve the relevant agent to determine the image download, download complete, download failed, when the picture download is completed will be handed to Sd_ Webimagedecoder does the image decoding process, and then also displays the picture through a series of callbacks to the Uiimageview+webcache to the front. The downloaded images will also be saved to the Sd_imagecache.

Most of this article borrowed from the author of this life carefree articles, and then personal summary.

iOS downloads cache with Sdwebimage pictures

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.