iOS third-party network picture loading-Sdwebimage notes

Source: Internet
Author: User
Tags md5 digest

Sdwebimage is hosted on GitHub. Https://github.com/rs/SDWebImage

This class library provides a uiimageview category to support the loading of remote pictures from the network. Features such as cache management, asynchronous download, same URL download count control, and optimization.
Use the Demo code:

UITableView using the Uiimageview+webcache class (basic application, a category of Uiimageview)

Premise #import Import the Uiimageview+webcache.h file, and then under TableView Cellforrowatindexpath: Method:



-(UITableViewCell *) TableView: (UITableView *) TableView cellforrowatindexpath:(Nsindexpath *) Indexpath {

static NSString *myidentifier = @ "Myidentifier";

UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier: Myidentifier];

if (cell = = nil) {

cell = [[[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault Reuseidentifier:myidentifier] Autorelease ];

}

Here we use the new provided Setimagewithurl:method to load the Web image

[Cell.imageview setimagewithurl: [nsurl urlwithstring:@ "http://www.domain.com/path/to/ Image.jpg"] placeholderimage:[uiimage imagenamed:@" Placeholder.png "];

Cell.textLabel.text = @ "My text";

return cell;

}


Basic code: [ImageView setimagewithurl:[nsurl urlwithstring:@ "http://www.domain.com/path/image.jpg"];

Use the Sdwebimagemanager class: You can do some asynchronous loading work.

Sdwebimagemanager *manager = [Sdwebimagemanager Sharedmanager];

UIImage *cachedimage = [manager Imagewithurl:url]; //Load the pictures that need to be cached in

if (cachedimage) {

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

Use the cached image immediatly

} Else {

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

Start an async download

[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 {

Do something with the downloaded image

}

Stand-alone asynchronous image download

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

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 want to use StoreImage:forKey:toDisk in memory cache only: The third parameter of the method takes a negative value

To replace.


Sdwebimage supports asynchronous image download + cache, providing Uiimageview+webcacha category for ease of use. Record the flow of sdwebimage loading pictures.

  1. Entry setImageWithURL:placeholderImage:options: The placeholderimage is displayed first, and then the Sdwebimagemanager is processed based on the URL.
  2. Enter Sdwebimagemanager-downloadwithurl:delegate:options:userinfo:, to Sdimagecache from the cache to find whether the picture has been downloaded QueryDiskCacheForKey:delegate:userInfo:.
  3. First from the memory picture cache to find if there is a picture, 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 no memory is in the cache, the build nsinvocationoperation is added to the queue to start looking for pictures from the hard disk if it is already cached.
  6. Try to read the picture file according to Urlkey in the hard disk cache directory. This step is performed at Nsoperation, so the callback notifydelegate is returned to the main thread :.
  7. If the previous action reads a picture from the hard disk, the picture is added to the in-memory cache (if the free memory is too small, the memory cache is emptied first). Sdimagecachedelegate callback ImageCache:didFindImage:forKey:userInfo:. And then callback the display image.
  8. If the picture is not read from the hard disk cache directory, the picture is not present in all caches, the picture needs to be downloaded, and the callback ImageCache:didNotFindImageForKey:userInfo:.
  9. Share or regenerate a downloader sdwebimagedownloader start downloading pictures.
  10. Image download by nsurlconnection to do, to achieve the relevant delegate to determine the picture download, download complete and download failed.
  11. Connection:didreceivedata: The use of ImageIO to download the progress by the picture loading effect.
  12. Connectiondidfinishloading: After the data download is finished, give Sdwebimagedecoder to do the image decoding processing.
  13. The image decoding process is done in a nsoperationqueue and does not slow down the main thread UI. If there is a need to download the image two times, it is best to complete here, the efficiency will be much better.
  14. In the main thread Notifydelegateonmainthreadwithinfo: announce the decoding complete, ImageDecoder:didFinishDecodingImage:userInfo: callback to Sdwebimagedownloader.
  15. Imagedownloader:didfinishwithimage: callback to Sdwebimagemanager tell the picture download complete.
  16. Notify all downloaddelegates download complete, callback to show the image where needed.
  17. Save the picture to Sdimagecache, the memory cache and the hard disk cache are saved at the same time. Writing files to the hard disk is also done in a separate nsinvocationoperation to avoid slowing down the main thread.
  18. 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.
  19. SDWI also offers Uibutton+webcache and Mkannotationview+webcachefor ease of use.
  20. Sdwebimageprefetcher can pre-download images for later use.

The role of the Sdwebimage library:
The task of asynchronously loading a replacement picture is achieved by extending the category of Uiimageview.

The main objects to use:
1, Uiimageview (webcache) category, ingress encapsulation, implementation of reading the image after the completion of the callback
2, Sdwebimagemanager, the management of the picture Transfer station, record those pictures are reading.
Read the cache to the downlevel (call Sdimagecache), or read the object to the network (call Sdwebimagedownloader).
Implement callbacks for Sdimagecache and Sdwebimagedownloader.
3, Sdimagecache, according to the URL of the MD5 digest to store and read the picture (Implementation exists in memory or there are two implementations of the hard disk)
Implement picture and memory cleanup work.
4, Sdwebimagedownloader, according to the URL to read data to the network (to achieve partial read and all read and then notify callback two ways)

Other classes:
Sdwebimagedecoder, an asynchronous image was decompressed??
I do not understand why we should do such a process at present. (now clear, functional explanations see below)

Interesting points:
1, Sdimagecache is how to do data management?
Sdimagecache is divided into two parts, one is the memory level, the other is the hard disk level.
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.

2, why must do decoder?
Through this blog: http://www. cocoanetics.com/2011/10/avoiding-image-decompression-sickness/
Now I understand that since UIImage's Imagewithdata function is to extract data into a ARGB image every time a drawing is made,
So in each drawing, there will be a decompression operation, so inefficient, but only the instantaneous memory requirements.
In order to improve the efficiency through the sdwebimagedecoder will be wrapped in data under the resource decompression, and then draw on another picture, so that the new picture will no longer need to re-extract.

This practice is typical of space-time-changing practices.

iOS third party network picture loading-Sdwebimage notes (GO)

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.