Swift's sdwebimage third-party framework

Source: Internet
Author: User
Tags md5 digest

[Uiimageview Setimagewithurl:]: Unrecognized selector sent to instance solution

The first time configuration, because Baidu took the tutorial, so one-time success

Results The second time did not go to Baidu, the result is tragic, and then find the previous configuration tutorial can not find

1. Select items, right click Add Files to XXXX

2, find Sdwebimage. Xcodeproj, and join the project

3. In the link Binary with Libraries tab in build phases, add Imageio.framework, Libsdwebimage.a

4. Find other Linker Flags in the Linking tab in Build settings, double-click the right area, click the + button in the pop-up box, and enter-OBJC

5. Build the project Bridge file, enter the reference code #import <SDWebImage/UIImageView+WebCache.h>

About the configuration of the bridge file, the small partners can Baidu a bit, but there is a skill, build a. h and. m files

Then copied to the Swift project, the system will prompt, whether to automatically establish the bridge file, click OK, Xcode will automatically help us to build the bridge file, and the configuration is not error ~ ~ ~

Finally, call the next sdwebimage in the extended method, run, success, over

Sdwebimage use
    • Type of sharing: game development related
[Pre] 1.storeimage:forkey:todisk://HDD Slow
2.setimagewithurl:placeholderimage://Memory Cache
3. Standalone cache image See the example below

[/pre]
Sdwebimage provides the following three category for caching.
    • Mkannotationview (Webcache)
    • UIButton (Webcache)
    • Uiimageview (Webcache)
take the most commonly used Uiimageview as an example:
  1. Uiimageview+webcache:setimagewithurl:placeholderimage:options: The Placeholderimage is displayed first, and the Sdwebimagemanager is based on the URL To find a picture locally.
  2. SDWebImageManager:downloadWithURL:delegate:options:userInfo:SDWebImageManager is to uiimageview+ Webcache classes linked with Sdimagecache, SDImageCache:queryDiskCacheForKey:delegate:userInfo: Used to find images from the cache based on CacheKey is already in the cache
  3. If there is already a picture cache in memory, Sdwebimagemanager will callback SDImageCacheDelegate:imageCache:didFindImage:forKey:userInfo:
  4. The Uiimageview+webcache callback SDWebImageManagerDelegate:webImageManager:didFinishWithImage: To display the picture.
  5. If there is no picture cache in memory, then the build nsinvocationoperation is added to the queue to find whether the picture has been cached from the hard disk.
  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.
  18. Write files to the hard disk in a separate nsinvocationoperation to avoid slowing down the main thread.
  19. If you are running on iOS, Sdimagecache will register notification to uiapplicationdidreceivememorywarningnotification when initializing and Uiapplicationwillterminatenotification, in memory warning, clean up the memory image cache, the end of the application to clean up the expired image.
  20. Sdwebimageprefetcher can pre-download images for later use.


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:

[Pre] 1-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {
2 static NSString *myidentifier = @ "Myidentifier";
3 UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:myidentifier];
4 if (cell = = nil) {
5 cell = [[[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault Reuseidentifier:myidentifier] Autorel Ease];
6}
7//The new provided Setimagewithurl:method to load the Web image
8 [Cell.imageview setimagewithurl:[nsurl urlwithstring:@ "Http://www.domain.com/path/to/image.jpg"] Placeholderimage:[uiimage imagenamed:@ "Placeholder.png"];
9 Cell.textLabel.text = @ "My text";
Ten return cell;
}[/pre]
[pre] Basic code: [imageview setimagewithurl:[nsurl urlwithstring:@ "http://www.domain.com/ Path/image.jpg "]);  
[/pre] uses the Sdwebimagemanager class: You can do some asynchronous loading work.  

[Pre] 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
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];
}[/pre]
[Pre] of course your class wants to implement the Sdwebimagemanagerdelegate protocol, and to implement the webimagemanager:didfinishwithimage of the Protocol: method.
[/pre] [pre]//The next download completes, call the callback method, so that the downloaded picture display
-(void) Webimagemanager: (Sdwebimagemanager *) Imagemanager didfinishwithimage: (UIImage *) Image {
Do something with the downloaded image
}[/pre] [Pre] standalone asynchronous image download
You may use asynchronous image download alone, you must use Downloaderwithurl:delegate: To create a Sdwebimagedownloader instance. [/pre] [Pre]downloader = [Sdwebimagedownloader downloaderwithurl:url delegate:self];
[/pre] [Pre] This method of Sdwebimagedownloaderdelegate protocol imagedownloader:didfinishwithimage: The download will start and finish immediately when it is invoked. [/pre] [Pre]
Standalone asynchronous image caching [The/pre][pre]sdimagecache class provides an instance of creating an empty cache and uses method Imageforkey: To find the current cache.
[/pre] [Pre]uiimage *mycachedimage = [[Sdimagecache Sharedimagecache] imagefromkey:mycachekey]; [/pre] [Pre]
Storing an image to the cache is the way to use Storeimage:forkey:[/pre] [Pre][[sdimagecache Sharedimagecache] Storeimage:myimage Forkey:mycachekey]; [/pre][Pre] 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. [/pre]

Example: Manual Clear Caching

1. Find the Sdimagecache class
2. Add the following method:

    -(float) checktmpsize
  1. {
  2. float totalsize = 0;
  3. Nsdirectoryenumerator *fileenumerator = [[Nsfilemanager Defaultmanager] enumeratoratpath:diskcachepath];
  4. For (NSString *filename in FileEnumerator)
  5. {
  6. NSString *filepath = [Diskcachepath stringbyappendingpathcomponent:filename];
  7. Nsdictionary *attrs = [[Nsfilemanager Defaultmanager] Attributesofitematpath:filepath Error:nil];
  8. unsigned long long length = [Attrs fileSize];
  9. TotalSize + = length/1024.0/1024.0;
  10. }
  11. NSLog (@ "tmp size is%.2f", totalsize);
  12. return totalsize;
  13. }


3. Use in Settings like this

    #pragma clean up cached pictures
  1. -(void) cleartmppics
  2. {
  3. [[Sdimagecache Sharedimagecache] cleardisk];
  4. [[Sdimagecache Sharedimagecache] clearmemory];//dispensable
  5. DLog (@ "clear disk");
  6. float tmpsize = [[Sdimagecache Sharedimagecache] checktmpsize];
  7. NSString *clearcachename = tmpsize >= 1? [NSString stringwithformat:@ "cleanup cache (%.2FM)", tmpsize]: [NSString stringwithformat:@ "clean cache (%.2FK)", tmpsize * 1024];
  8. [Configdataarray Replaceobjectatindex:2 Withobject:clearcachename];
  9. [Configtableview Reloaddata];
  10. }

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.

Swift's sdwebimage third-party framework

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.