iOS Web data download and JSON parsing

Source: Internet
Author: User

Introduction to iOS Web data download and JSON parsing

In this article, I'm going to show you how to use nsurlconnection to download data from the Web, how to parse the downloaded JSON format, and how to display the asynchronous download display of data and images.

The knowledge points involved:

1.NSURLConnection Asynchronous Download and encapsulation

2.JSON format and JSON format parsing

3. Data display and use Sdwebimage to display images asynchronously

Content 1. Introduction to basic knowledge of network download

What is a Web application?

In general, applications need to load data, and all applications that require network-loaded data can be called network applications

The program structure of network application

    

Common forms of network interfaces

Common data formats

General flow of interface development

2.NSURLConnection use

NSString Downloading data synchronously

    //the URL address used in HTTP//http://protocol used by address//iappfree.candou.com host address (domain name and IP)//: 8080 Host port//free/applications/limited Web program file path//currency=rmb&page=1&category_id= Program parameters (Parameters & Segmentation)NSString *urlstring =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //Download Data//production of Nsurl objects by addressNserror *error =Nil; Nsurl*url =[Nsurl urlwithstring:urlstring]; NSString*content = [[NSString alloc] Initwithcontentsofurl:url encoding:nsutf8stringencoding error:&ERROR]; if(Error = =Nil) {NSLog (@"connent =%@", content); }    Else{NSLog (@"Download Failed"); }

#pragmaMark-Asynchronous Download-(void) testnsstringasyncdownloaddata{NSString*urlstring =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //Initialize_data =[[Nsmutabledata alloc] init]; //an asynchronous URL connection request was initiated//async: Starts the download after executing the method, immediately returns//the download process is performed in the background (multithreaded)_connection = [[Nsurlconnection alloc] initwithrequest:[nsurlrequest requestwithurl:[nsurl URLWithString:urlString]]Delegate: Self startimmediately:yes]; NSLog (@"initwithrequest Execution Complete");}//Proxy Method: Received the server response execution- (void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{NSLog (@"receiving server response execution");}//Proxy method: Executes when the data is received//Note: When the data is large, it may be executed multiple times- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[_data appenddata:data];}//Proxy method: The data download is complete- (void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSString*str =[[NSString alloc] Initwithdata:_data encoding:nsutf8stringencoding]; NSLog (@"str =%@", str); //parsing JSON//function: JSON data converted to Nsarray or nsdictionaryNsdictionary *dict =[nsjsonserialization jsonobjectwithdata:_data options:nsjsonreadingmutablecontainers Error:nil];//NSLog (@ "%@", dict);Nsarray *applist = dict[@"Applications"];  for(Nsdictionary *appdictinchapplist) {NSLog (@"name =%@", appdict[@"name"]); }    }//Download failed call- (void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"error =%@", error);}//nsurlconnection sync Download- (void) testnsstringsyncdownloaddata{NSString*urlstring =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //send a sync URL request//nsurlresponse 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); }    Else{NSLog (@"Download Failed"); }}//Sync Download- (void) testnsstringdownloaddata{//the URL address used in HTTP//http://protocol used by address//iappfree.candou.com host address (domain name and IP)//: 8080 Host port//free/applications/limited Web program file path//currency=rmb&page=1&category_id= Program parameters (Parameters & Segmentation)NSString *urlstring =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //Download Data//production of Nsurl objects by addressNserror *error =Nil; Nsurl*url =[Nsurl urlwithstring:urlstring]; NSString*content = [[NSString alloc] Initwithcontentsofurl:url encoding:nsutf8stringencoding error:&ERROR]; if(Error = =Nil) {NSLog (@"connent =%@", content); }    Else{NSLog (@"Download Failed"); }}

Because the downloader is used frequently, it can be encapsulated for invocation. The following is the encapsulated download block:

#import "ZYHttpRequest.h"//Elimination of Performselector warnings#pragmaClang diagnostic ignored "-warc-performselector-leaks"//class Expansion//Project Practice://Some strength variables used internally, do not want to put in the header file, put in this (. m file)@interfaceZyhttprequest () <NSURLConnectionDataDelegate>{nsurlconnection*_connetion; NSString*_url; ID_target; SEL _action;}@end@implementationzyhttprequest//role: Incoming URL, after the download is complete, execute the action method in the target object- (void) Requestwithurl: (NSString *) URL target: (ID) Target action: (SEL) action{_url=URL; _target=Target; _action=Action; //initiating a URL request asynchronous request_data =[[Nsmutabledata alloc] init]; _connetion= [[Nsurlconnection alloc] initwithrequest:[nsurlrequest requestwithurl:[nsurl Urlwithstring:url]]Delegate: Self startimmediately:yes];}//Proxy method: Executes when the data is received//Note: When the data is large, it may be executed multiple times- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[_data appenddata:data];}//Proxy method: Data Download complete Call- (void) Connectiondidfinishloading: (Nsurlconnection *) connection{//after the download is complete, the method of saving is executed    if(_target &&[_target respondstoselector:_action])    {[_target performselector:_action withobject:self]; }}@end

3.JSON format description and Formatting tools

Json

JavaScript Object Notation

[] represents the array, corresponding to the Nsarray

That represents the data that is tied

{} represents the dictionary, corresponding to the Nsdictionary

"Ta" means string, corresponding to NSString

20 Correspondence NSNumber

    //parsing JSON//function: JSON data converted to Nsarray or nsdictionaryNsdictionary *dict =[nsjsonserialization jsonobjectwithdata:_data options:nsjsonreadingmutablecontainers Error:nil];//NSLog (@ "%@", dict);Nsarray *applist = dict[@"Applications"];  for(Nsdictionary *appdictinchapplist) {NSLog (@"name =%@", appdict[@"name"]);
4. Implementation of a complete page (including model creation, use of sdwebimage)

iOS Web data download and JSON parsing

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.