"IOS" Network Load picture cache with Sdwebimage

Source: Internet
Author: User

Loading network pictures can be said to be a must in network applications. If the simple to download pictures, and not to do multi-threading, caching and other technologies to optimize, loading pictures when the effect and user experience will be very poor.

First, the way to implement loading pictures

Tips

*IOSAll network accesses are asynchronous. (ownThe thread to download)*Normalto beModelIncreaseUIImagePropertiesthe way to do that isMemory Cache(the next boot also needs to be reloaded from the network),and to do the local cache.,and I have to manuallypictures downloaded on the storage network.*to speed up access,You need to get it yourself.Cache.(memory Cache or local cache)*When the picture is not downloaded, also set thePlaceholder Pictures.

The following code uses Nsoperation to open an asynchronous thread to download the picture and replace the placeholder picture When the download is complete.

xnviewcontroller.m//Load network pictures, common with nsoperation to do.////Created by Neng on 14-7-7.//Copyright (c) 2014 Neng. All rights reserved.//#import "XNViewController.h" #import "XNApp.h" @interface Xnviewcontroller () @property (nonatomic , strong) Nsarray *applist, @property (nonatomic, strong) Nsoperationqueue *queue; @end @implementation xnviewcontroller# pragma mark-Lazy load-(Nsoperationqueue *) Queue {if (!_queue) _queue = [[Nsoperationqueue alloc] Init];return _queue;} Can be extracted and written into the model-(Nsarray *) applist {if (!_applist) {//1. Loading plist into an array nsurl *url = [[NSBundle mainbundle] urlforresource:@ " Apps.plist "Withextension:nil"; Nsarray *array = [Nsarray arraywithcontentsofurl:url];//2. Traversal array Nsmutablearray *arraym = [Nsmutablearray array];  [Array Enumerateobjectsusingblock: ^ (id obj, Nsuinteger idx, BOOL *stop) {[Arraym Addobject:[xnapp appwithdict:obj]]; The array is stored in a dictionary, converted to an App object and then added to the array}];_applist = [Arraym copy];} return _applist;} -(void) viewdidload {[Super Viewdidload];self.tableview.rowheight = 88;//NSLog (@ "applist-%@", _applist);} #pragma mark-Data source Method-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {return Self.appList.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {static NSString *id = @ "Cell"; UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id];//with model to populate each Cellxnapp *app = self.applist[  Indexpath.row];cell.textlabel.text = App.name; Set text//settings Image: The default image is used when the image in the model is nil, and the image is downloaded. Otherwise, use the memory in the model to cache the image. if (!app.image) {cell.imageView.image = [UIImage imagenamed:@ "User_default"];[ Self Downloadimg:indexpath];} else {//directly with memory cache in the model cell.imageView.image = App.image;} NSLog (@ "cell--%p", cell); return cell;} /** always remember to modify the display through the model. Instead of trying to directly modify the display */-(void) downloadimg: (Nsindexpath *) Indexpath {Xnapp *app = Self.applist[indexpath.row];//Get the model of the row corresponding [ Self.queue addoperationwithblock: ^{nsdata *imgdata = [NSData datawithcontentsofurl:[nsurl URLWithString:app.icon]; /Get image data UIImage *image = [UIImage Imagewithdata:imgdata];        Updating the UI in the main thread [[Nsoperationqueue mainqueue] Addoperationwithblock: ^{//Modify the data by modifying the model app.image = image; Refreshes the specified table row [Self.tableview Reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationnone];} ];}];} @end


The above code simply does the memory cache, and every time you re-enter the app, it will be downloaded again from the Web. If you want to continue optimizing the above code, you need to implement the local cache yourself.


second, the use of third-party framework Sdwebimage. (very good)

*features :dependent libraries are rare. Fully functional. *Automatic ImplementationDisk Cache:*The cached image name isMD5to encrypt theafter the name is named. (because the string of encryption is unique.)*[ImageViewSd_setimagewithurl: V.fullimageurl Placeholderimage:[uiimage imagenamed:@ "xxxxx"].*That's one way to do it.Multithreading\with buffer equivalentFruit.(methods available with parameters,specific documents to be worth seeing)
the code after modifying the above method with Sdwebimage can be simplified to:
#pragma mark-Data source Method-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {return Self.appList.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {static NSString *id = @ "Cell"; UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id];//with model to populate each Cellxnapp *app = self.applist[  Indexpath.row];cell.textlabel.text = App.name; Set the text////the image: Use the default image when the image is nil in the model, and download the image. Otherwise, use the memory in the model to cache the image.//if (!cell.imageview.image) {//cell.imageview.image = [UIImage imagenamed:@ "User_default"];////[self Downloadimg:indexpath];//}//else {////directly with the memory cache in the model//cell.imageview.image = app.image;//}//Use Sdwebimage to complete the above functionality. For imageview.//, an asynchronous download is automatically implemented. Picture local cache. Network download. Auto-set placeholders. [Cell.imageview sd_setimagewithurl:[nsurl URLWithString:app.icon] placeholderimage:[uiimage imagenamed:@ "User_ Default "]];return cell;} /** always remember to modify the display through the model. Instead of trying to directly modify the display *///-(void) downloadimg: (Nsindexpath *) Indexpath {//xnapp *app = Self.applist[indexpAth.row]; Get a model for a row////[self.queue addoperationwithblock: ^{//nsdata *imgdata = [NSData datawithcontentsofurl:[nsurl URLWithS Tring:app.icon]]; Get image Data//UIImage *image = [UIImage imagewithdata:imgdata];//////update ui//in main thread [[Nsoperationqueue Mainqueue] AddO Perationwithblock: ^{////Modify the data by modifying the model//App.image = image;////refresh the specified table row//[Self.tableview rel Oadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationnone];//}];//}];//} @end

Some of the parameters in Sdwebimage:*sdwebimageretryfailed = 1<< 0,default option, retry after failure*sdwebimagelowpriority = 1<< 1,use low-priority*sdwebimagecachememoryonly = 1<< 2,use only memory cache*sdwebimageprogressivedownload = 1<< 3,Show Current Progress*sdwebimagerefreshcached = 1<< 4,Refresh Cache*Sdwebimagecontinueinbackground =1 << 5,continue downloading images in the background*sdwebimagehandlecookies = 1<< 6,processingCookies*sdwebimageallowinvalidsslcertificates= 1 << 7,allows for invalidSSLValidation*sdwebimagehighpriority = 1<< 8,High-priority*Sdwebimagedelayplaceholder = 1<< 9delay Display placeholder picture

Reprint Please specify the Source:http://blog.csdn.net/xn4545945  



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.