Cat Learn iOS (55) Multi-threaded network picture download frame Sdwebimage

Source: Internet
Author: User
Tags ssl certificate

Cat Share, must boutique

Original articles, welcome reprint. Reprint Please specify: Sanayu's Blog
Address: http://blog.csdn.net/u013357243?viewmode=contents

Effect:

Code:
- (Nsarray*) apps{if(!_apps) {Nsarray*dictarray = [Nsarrayarraywithcontentsoffile:[[NSBundleMainbundle] pathforresource:@"Apps.plist"OfType:Nil]];Nsmutablearray*apparray = [NsmutablearrayArray]; for(nsdictionary*dict in Dictarray) {Hmapp *app = [Hmapp appwithdict:dict];        [Apparray Addobject:app];    } _apps = Apparray; }return_apps;} - (void) viewdidload{[SuperViewdidload];}#pragma mark-Data source methods- (Nsinteger) TableView: (UITableView*) TableView numberofrowsinsection: (Nsinteger) section{return  Self. Apps. Count;} - (UITableViewCell*) TableView: (UITableView*) TableView Cellforrowatindexpath: (Nsindexpath*) indexpath{Static NSString*id = @"App";UITableViewCell*cell = [TableView dequeuereusablecellwithidentifier:id];if(!cell) {cell = [[UITableViewCellAlloc] Initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:id]; }//Get Data ModelHmapp *app = Self. Apps[Indexpath. Row];//Set the cell titleCell. Textlabel. Text= App. Name;//Set number of downloads for cellCell. Detailtextlabel. Text= App. Download;//Positioning pictures    UIImage*place = [UIImageimagenamed:@"57437179_42489b0"];//Use the Sdwebimage framework to resolve an asynchronous download, cache, sandbox cache and other operations, and set the picture to the cell[Cell. ImageViewsetimagewithurl:[NsurlUrlwithstring:app. Icon] Placeholderimage:place];returnCell;}
Self-implementation picture of the image of an asynchronous download sandbox cache operation (interview)

Sdwebimage

Brief introduction:
1:sdwebimage is: The famous online image processing framework in iOS.
2: Included features: Picture download, picture cache, download progress monitor, GIF processing and so on.
3: The usage is extremely simple, the function is very powerful, greatly improved the network picture processing efficiency.
4: More than 90% of iOS projects in China have its shadow.

Use steps

The first step is to download the Sdwebimage and import the project. GitHub Escrow Address Https://github.com/rs/SDWebImage

Step two, import the header files where needed

#import "UIImageView+WebCache.h"

The third step, call Sd_setimagewithurl: And so on. There are no SD openings in the old version.

Two: Focus: A few common methods to remember 1 common methods
//设置下载图片的链接和站位图片- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
//设置下载图片的链接和站位图片以及一个选项的集合options- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;

Sdwebimageoptions (options in the method above)
* sdwebimageretryfailed: After the download fails, it will be automatically re-downloaded
* Sdwebimagelowpriority: Automatically pauses some internal download operations while UI interaction is in progress
* sdwebimageretryfailed | Sdwebimagelowpriority: Has the above 2 functions

    //Retry after failuresdwebimageretryfailed =1<<0,//ui starts downloading during the interaction, resulting in delayed downloads such as Uiscrollview deceleration. Sdwebimagelowpriority =1<<1,//Memory cache onlySdwebimagecachememoryonly =1<<2,//This flag can be incrementally downloaded, and the displayed image is progressively downloaded inSdwebimageprogressivedownload =1<<3,//Refresh Cachesdwebimagerefreshcached =1<<4,//Background DownloadSdwebimagecontinueinbackground =1<<5,//nsmutableurlrequest.httpshouldhandlecookies = YES;Sdwebimagehandlecookies =1<<6,//allow use of invalid SSL certificate     //sdwebimageallowinvalidsslcertificates = 1 << 7,     //Priority DownloadSdwebimagehighpriority =1<<8,//Delay placeholderSdwebimagedelayplaceholder =1<<9,//Change animation imageSdwebimagetransformanimatedimage =1<<Ten,

Set the link and position picture of the downloaded picture and execute it after completion (completed completed)

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;

This method is used to make the download progress bar

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
2 Memory Processing: When the app receives a memory warning

/**
* When the app receives a memory warning
*/
-(void) applicationdidreceivememorywarning: (uiapplication *) application
{
Sdwebimagemanager *mgr = [Sdwebimagemanager Sharedmanager];

// 1.取消正在下载的操作[mgr cancelAll];// 2.清除内存缓存[mgr.imageCache clearMemory];

}

3 Sdwebimage Internal implementation process
  1. Entry SetImageWithURL:placeholderImage:options: The Placeholderimage is displayed first, and then the Sdwebimagemanager is processed based on the URL.
    1. Enter Sdwebimagemanager-downloadwithurl:delegate:options:userinfo:, to Sdimagecache from the cache to find whether the picture has been downloaded Querydiskcacheforkey :d Elegate:userinfo:.
    2. 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.
    3. Sdwebimagemanagerdelegate callback Webimagemanager:didfinishwithimage: to Uiimageview+webcache and other front-end display pictures.
    4. 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.
    5. 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:.
    6. 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.
    7. 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:.
    8. Share or regenerate a downloader sdwebimagedownloader start downloading pictures.
    9. Image download by nsurlconnection to do, to achieve the relevant delegate to determine the picture download, download complete and download failed.
    10. Connection:didreceivedata: The use of ImageIO to download the progress by the picture loading effect.
    11. Connectiondidfinishloading: After the data download is finished, give sdwebimagedecoder to do the image decoding processing.
    12. 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.
    13. In the main thread Notifydelegateonmainthreadwithinfo: announce the decoding complete, ImageDecoder:didFinishDecodingImage:userInfo: callback to Sdwebimagedownloader.
    14. Imagedownloader:didfinishwithimage: Callback to Sdwebimagemanager tell the picture download complete.
    15. Notify all downloaddelegates download complete, callback to show the image where needed.
    16. 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.
    17. 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.
    18. SDWI also offers uibutton+webcache and mkannotationview+webcache for ease of use.
    19. Sdwebimageprefetcher can pre-download images for later use.
Recommendations for the use of third-party frameworks

1. Purpose of the third-party framework
A: Development efficiency: rapid development, others packaged a line of code top of their own write n line
B: To use the best implementation of this feature

2. Excessive third-party frameworks, many disadvantages (negligible)
A: Manage, upgrade, update
B: Third-party framework has bugs waiting for the author to resolve
C: The author of a third-party framework unfortunately dies, stops updating (potential bug unsolved)
D: Feel: Own good water

For example, in the streaming media: Play online video, audio (side download side play) and other requirements.
If you do what you need we know very well the format of audio and video files. And each video has its own decoding method (c\c++), it is really difficult, not a few years of deep research really no results

4. Summary
1> standing on the shoulders of giants programming
2>, it's all right. Use a more stable third-party framework

PS: (Sdwebimage internal implementation process refers to the 6DUXZ blog part of the material from the wisdom of the Black horse ppt)

PS2: Blog Content A lot of things people's class content, but each of the paintings are cats carefully sorted out, the purpose is to facilitate their own review, if you want to learn, very welcome to make friends.

Cat Learn iOS (55) Multi-threaded network picture download frame Sdwebimage

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.