iOS Development Practice cell Download image (Nsoperation)

Source: Internet
Author: User

Scrolling list cell pictures are downloaded from the server and are used to efficiently download display images using multithreading and caching techniques.

Cell Download Picture ideas:


1, the definition of images dictionary storage after downloading the picture (image download URL as key, image as value) cell picture first go to the images dictionary to find, not down (look in the sandbox).

2, find whether the sandbox exists, if there is to set the cell picture, otherwise display placeholder picture (enhance experience) and open the thread to download pictures.

3. Define dictionary operations all download operations (URL is key,operation object is value ). Determine If the download operation exists, or create a download if there is a description download.

4. After the download is complete, update the main thread: Add the picture to the images dictionary, remove the operation from the Operations dictionary (to prevent the operations from getting bigger, to ensure that the download fails, you can re-download ), save the picture in the sandbox, and refresh the table.


Case: Application Management Interface Cell

1. Application Model

App.h

#import <Foundation/Foundation.h> @interface app:nsobject//app name @property (nonatomic,copy) NSString *name;// Download Volume @property (nonatomic,copy) nsstring *download;//icon address @property (nonatomic,copy) nsstring *icon;+ (instancetype) Appwithdict: (nsdictionary *) dict; @end


app.m

#import "App.h" @implementation app+ (Instancetype) appwithdict: (nsdictionary *) dict{    app *app = [[App alloc]init];    [App Setvaluesforkeyswithdictionary:dict];    return app;} @end


2. Define queue, store operation dictionary, store picture dictionary, apply app variable

App App@property (nonatomic,strong) Nsmutablearray *apps;//Store all downloaded images queue @property (Nonatomic,strong) NSOperationQueue *queue;//Store all download operations (URL is key,operation object is value) @property (nonatomic,strong) nsmutabledictionary *operations;// Store all downloaded images @property (nonatomic,strong) nsmutabledictionary *images; #pragma lazy load-(Nsmutablearray *) apps{if (_apps==nil        {Nsmutablearray *apparr = [Nsmutablearray array];        Remove plist file Conversion dictionary nsstring *file = [[NSBundle Mainbundle] pathforresource:@ "apps" oftype:@ "plist"];        Nsarray *dictarr = [Nsarray arraywithcontentsoffile:file];            Dictionary to model for (Nsdictionary *dict in Dictarr) {app *app = [app appwithdict:dict];        [Apparr Addobject:app];    } _apps = Apparr; } return _apps;}    -(Nsoperationqueue *) queue{if (!_queue) {self.queue = [[Nsoperationqueue alloc]init]; } return _queue;} -(Nsmutabledictionary *) operations{if (!_operations) {self.operations = [[NsmutabledictionaryAlloc]init]; } return _operations;}    -(Nsmutabledictionary *) images{if (_images) {self.images = [[Nsmutabledictionary alloc]init]; } return _images;}


3. Set cell, thread download picture

#pragma mark-table View data source-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView {return 1;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section {return self.apps.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {static Nsstri    ng *id = @ "App";    UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id];    if (!cell) {cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:id];        }//Remove model APP *app = Self.apps[indexpath.row];    Set cell Cell.textLabel.text = App.name;        Cell.detailTextLabel.text = App.download;    The image URL corresponding to the UIImage UIImage *image = Self.images[app.icon] is taken from the images cache first;    if (image) {//Description picture has been successfully downloaded (successfully cached) Cell.imageView.image = image; }else{//Description The picture has not been downloaded successfully (not cached)//Get caches path, stitching file path NSString *file = [[NssearchpathfordirectoriesindomaiNS (Nscachesdirectory, Nsuserdomainmask, YES) Lastobject]stringbyappendingpathcomponent:[app.icon lastPathComponent                 ]];        First remove the picture from the sandbox nsdata *data = [NSData datawithcontentsoffile:file];        This file exists in the if (data) {//Sandbox cell.imageView.image = [UIImage imagewithdata:data];                       This file does not exist in the}else{//sandbox//display placeholder picture cell.imageView.image = [UIImage imagenamed:@ "placeholder"];        Download image [self Download:app.icon indexpath:indexpath]; }} return cell;} -(void) Download: (NSString *) imageUrl Indexpath: (Nsindexpath *) indexpath{//Take out the download operation under the current picture URL (Operations object) Nsblocko    Peration *operation = Self.operations[imageurl];    if (operation) return;    __weak typeof (self) appsvc = self;        Operation = [Nsblockoperation blockoperationwithblock:^{nsurl *url = [Nsurl Urlwithstring:imageurl]; NSData *data = [nsdata datawithcontentsofurl:url];//download picture UIImage *image = [UIImage imagewithdata:d ata];//converted to image//back to live thread [[Nsoperationqueue Mainqueue] addoperationwithblock:^{if (imag                                e) {//store in dictionary appsvc.images[imageurl] = image; The picture is saved in the sandbox solution)//uiimage-nsdata-file (files) nsdata *data = Uiimagepngrepresentation (                image); NSString *file = [[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) LastObject]                Stringbyappendingpathcomponent:[imageurl Lastpathcomponent]];                NSLog (@ "%@", file);                            [Data writetofile:file Atomically:yes]; }//Remove the download from the dictionary (to prevent operations from getting bigger, and to download again after the download fails) [Appsvc.operations removeobjectforkey:i                        Mageurl];        Refresh table [Appsvc.tableview Reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationnone];            }];        }]; Add an action to the queue [Self.queue AddOPeration:operation]; Add to the dictionary (this Code in order to resolve the duplicate download) Self.operations[imageurl] = operation;}


4. Stop downloading when the table is dragged, and start downloading when you stop dragging.

/** *  call */-(void) scrollviewwillbegindecelerating when the user starts to drag the table: (Uiscrollview *) scrollview{    //Pause Download    [ Self.queue Setsuspended:yes];} /** *  call */-(void) scrollviewdidenddragging when the user stops dragging the table: (Uiscrollview *) ScrollView willdecelerate: (BOOL) decelerate{    //Resume Download    [Self.queue setsuspended:no];}

5. Memory warning to remove all cache dictionaries.

-(void) didreceivememorywarning {    [super didreceivememorywarning];        Remove all download operation caches    [Self.queue cancelalloperations];    [Self.operations removeallobjects];    Remove all picture caches    [Self.images removeallobjects];}


Effect:


iOS Development Practice cell Download image (Nsoperation)

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.