4_1 the first day of network learning--Network data download

Source: Internet
Author: User

4_1 the first day of network learning--Network data download

1, the network data download includes the synchronous download and the asynchronous download, generally is uses the asynchronous download, the asynchronous download may utilize the Nsurlconnection this class .

2, the data format, has the JSON format (majority), the XML format. The JSON format is as follows :

{} represents a dictionary, [] represents an array, "" represents a string, 100 represents NSNumber

3, Analysis network interface

such as: @ "http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="

/HTTP (Address Use protocol) iappfree.candou.com (host address) 8080 (host port)

free/applications/limited (Network program file path)? currency=rmb&page=1&category_id= (Program parameters)

4, nsurlconnection the synchronization download code:

-(void) testnsurlconnectionsyncdownloaddata{//page-free interface onlyNSString *urlstring=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //send a sync URL request//nsurlrequest URL Request ObjectNsurl *url=[Nsurl urlwithstring:urlstring]; Nsurlrequest*request=[Nsurlrequest Requestwithurl:url]; Nserror*error=Nil; NSData*data=[nsurlconnection sendsynchronousrequest:request Returningresponse:nil error:&ERROR]; if(error==Nil) {NSString*str=[[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"str =%@", str); }    Else{NSLog (@"Download Failed"); }}

5, nsurlconnection the asynchronous download code:

-(void) testnsurlconnectionasyncdownloaddata{_data=[[Nsmutabledata alloc]init]; //page-free interface onlyNSString *urlstring=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //initiating an asynchronous URL request//Async: After executing the method, start the download_connection=[[nsurlconnection alloc]initwithrequest:[nsurlrequest Requestwithurl:[nsurl URLWithString:urlString]]Delegate: Self startimmediately:yes]; }//Here are the <NSURLConnectionDataDelegate> proxy methods//receiving server response execution-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{NSLog (@"receiving server response execution");}//execute when data is received//Note: When the data is large, it may be executed more than once-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[_data appenddata:data];}//when the data download is complete-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{//NSLog (@ "str =%@", [[NSString Alloc]initwithdata:_data encoding:nsutf8stringencoding]); //Parse JSON (convert JSON to Nsarray or nsdictionaryNsdictionary *dict=[nsjsonserialization jsonobjectwithdata:_data options:nsjsonreadingmutablecontainers Error:nil]; Nsarray*applist=dict[@"Applications"];  for(Nsdictionary *appdictinchapplist) {NSLog (@"name =%@", appdict[@"name"]); }}//Download Failed-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"Error =%@" , error);}

6. Package Nsurlconnection (Key)

First create a NSObject class,

#import <Foundation/Foundation.h>@interface  zjhttprequset:nsobject// data is used to save the downloaded @property (nonatomic,copy), nsmutabledata * data; // to a Web site, after the download is complete, execute the action method in target -(void) Requestwithurl: (nsstring *) URL target: (ID ) Target action: (SEL) action; @end
#import "ZJHttpRequset.h"#import "AppModel.h"//Elimination of Performselector warnings#pragmaClang diagnostic ignored "-warc-performselector-leaks"//class extension, some instance variables are used internally, and do not want to be placed in the header file, it can be placed inside the class extension. @interfaceZjhttprequset () <NSURLConnectionDataDelegate>{nsurlconnection*_connection; //used to save the URL that is stored in the target actionNSString *_url; ID_target; SEL _action;}@end@implementationZjhttprequset-(void) Requestwithurl: (nsstring *) URL target: (ID) Target action: (SEL) action{//Save the variables that are stored in_url=URL; _target=Target; _action=Action; //Remember to initialize data!!! _data=[[Nsmutabledata alloc]init]; //initiating an asynchronous URL request_connection=[[nsurlconnection alloc]initwithrequest:[nsurlrequest Requestwithurl:[nsurl URLWithString:url]]Delegate: Self startimmediately:yes];}//Nsurlconnection Proxy Method//Receive Data-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[_data appenddata:data];}//download Complete, execute method-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{if(_target&&[_target respondstoselector:_action])    {[_target performselector:_action withobject:self]; }    //The object in this is the class itself, in order to pass the received data}

And then pass in the network interface, using this encapsulated Nsurlconnection class to receive

@implementationViewcontroller- (void) viewdidload{[Super Viewdidload]; //Data InterfaceNSString *urlstring=@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //Initialize Array (tabelview group of total data)_dataarray =[Nsmutablearray array]; //Initialize self-encapsulated nsurlconnection class_request=[[Zjhttprequset alloc]init];        [_request requestwithurl:urlstring target:self Action: @selector (dealdownloadfinish:)]; //Create a table view[self Createtableview];}//methods that are triggered after the receive completes (using Performselector in the self-encapsulated URL Class)-(void) Dealdownloadfinish: (Zjhttprequset *) request{//JSON parsing, (getting an array or a dictionary, need to be viewed in the Jason Software)Nsdictionary *dict=[nsjsonserialization JSONObjectWithData:request.data options:nsjsonreadingmutablecontainers Error:nil]; Nsarray*applist=dict[@"Applications"]; //use the data model to save the data under the network interface, and then add the model to the TableView totals group     for(Nsdictionary *appdictinchapplist) {Appmodel*model=[[Appmodel alloc]initwithdict:appdict];    [_dataarray Addobject:model]; }    //after downloading the data, update the total group, be sure to refresh tableview!!! [_tableview reloaddata];}

7. Homework

ScrollView Slide

//First step: Initialize, download data from the network interface-(void) createscrollview{_alldata1=[Nsmutablearray array]; //Eason Chan Network interfaceNSString *urlstring=@"http://mapi.damai.cn/hot201303/nindex.aspx?cityid=0&source=10099&version=30602"; _request1=[[Lchttprequest alloc]init];    [_request1 requesturl:urlstring withtarget:self andaction: @selector (scrollviewdownload:)]; }//The second step: The method that triggered after downloading completes, the download good data to deposit the total group-(void) Scrollviewdownload: (Lchttprequest *) request{Nsarray*arr=[nsjsonserialization JSONObjectWithData:request.data options:nsjsonreadingmutablecontainers Error:nil];  for(Nsdictionary *dictincharr) {NSString*str=dict[@"Pic"];    [_alldata1 ADDOBJECT:STR]; } [self loadimage];}//The third step: According to the total number of downloads, change ScrollView contensize and set its ImageView-(void) loadimage{_scrollview.contentsize=cgsizemake ( the*_alldata1.count,0);  for(intI=0; i<_alldata1.count; i++) {Uiimageview*imageview=[[uiimageview Alloc]initwithframe:cgrectmake ( the*i,0, the,165)]; NSString*str=_alldata1[i];        [ImageView Setimagewithurl:[nsurl urlwithstring:str];    [_scrollview Addsubview:imageview]; }    //Set Pagecontrol_pagecontrol.numberofpages=_alldata1.count; _pagecontrol.enabled=NO;    [Self.view Bringsubviewtofront:_pagecontrol]; _pagecontrol.pageindicatortintcolor=[Uicolor Redcolor]; //Start the timer and let the Scroview slide[Nstimer Scheduledtimerwithtimeinterval:3.0target:self selector: @selector (scrollviewmove) Userinfo:nil repeats:yes];}//method of Timer triggering-(void) scrollviewmove{Cgpoint pp=_scrollview.contentoffset; if(pp.x== the* (_alldata1.count-1) ) {pp.x=0; _scrollview.contentoffset=pp; }    Else{pp.x+= the; [UIView animatewithduration:2.0animations:^{_scrollview.contentoffset=pp;    }]; }}//<UIScrllViewDelegate> Proxy Method Let Pagecontrol follow the move-(void) Scrollviewdidscroll: (Uiscrollview *) scrollview{intPage =scrollview.contentoffset.x/ the; _pagecontrol.currentpage=page;}

4_1 the first day of network learning--Network data download

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.