Network data download and JSON parsing

Source: Internet
Author: User

Introduction to iOS Web data download and JSON parsing

In this article, I will give you an introduction to how iOS uses nsurlconnection to download data from the Web, how to parse the downloaded JSON data format, and how to display the asynchronous download display of data and images.

The knowledge points involved are:

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?

For the Web application of iOS development, I feel that the iOS application that needs to access the network and get the server data for all functions can become a network application.

The program structure of network application

The network application structure has b/s browser/server, c/S client browser. The C/s structure has relatively faster response times because he reduces the necessary data transmission and handles more calculations or logic processing.

Common forms of network interfaces

iOS Web application Common Data Interface half is the HTTP form of the URL address, such as the Love Limit application first page of the data address is http://iappfree.candou.com:8080/free/applications/limited? Currency=rmb&page=1&category_id=

Some open source libraries are commonly used in projects to download data from this web site. such as Afnetworking

    

Common data formats

The usual network interface forms are Xml,json, and we are now talking about Json format, which we will design to XML in other posts.

2.NSURLConnection use

We can easily access the network by creating a URL and creating a link through a URL. Here are a few ways to get network data.

    // use URL address    in HTTP //   http://  Address Usage Protocol (ftp://)    //   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)

(1) data acquisition via URL synchronization

-(void) testnsstringdownloaddata{Nsurl*url = [Nsurl urlwithstring:@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=%d&category_id="]; NSLog (@"%@", URL); Nserror* ERROR =Nil; NSString*content = [[NSString alloc]initwithcontentsofurl:url encoding:nsutf8stringencoding error:&ERROR]; if(Error = =Nil) {NSLog (@"%@", content); }Else{NSLog (@"Download Failed"); }}

(2) simultaneous download via nsurlconnection

-(void) testnsurlconectionsyndownloaddata{NSString*str =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; Nsurl* URL =[Nsurl Urlwithstring:str];nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; Nserror*error =Nil; NSData*data = [Nsurlconnection sendsynchronousrequest:request returningresponse:nil error:&ERROR]; if(Error = =Nil) {NSString*string=[[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"str =%@",string); }Else{NSLog (@"failed"); }}

(3) The better way is by nsurlconnection asynchronous loading, in

The Nsurlconnectiondatadelegate proxy method implements the operation of the data download complete.
@interfaceNlviewcontroller () <NSURLConnectionDataDelegate>{nsurlconnection*_connection; Nsmutabledata*_data;}@end@implementationNlviewcontroller- (void) viewdidload{[Super Viewdidload]; //1. Load Data[self testnsurlconectionasyndownloaddata]; }-(void) testnsurlconectionasyndownloaddata{NSString*urlstring =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; _data=[[Nsmutabledata alloc]init]; //initializing a URL object with a URL stringNsurl *url =[Nsurl urlwithstring:urlstring]; //Create a Nsurlrequest object using a URLNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //Initializes a Nsurlconnection object and immediately begins accessing the data to handle the appropriate proxy method. _connection = [[Nsurlconnection alloc]initwithrequest:requestDelegate: Self startimmediately:yes];}#pragmaMark-Proxy Method-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{NSLog (@"Didreceiveresponse");}- (void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[_data Appenddata:data]; NSLog (@"Didreceivedata");}-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSLog (@"connectiondidfinishloading"); NSString*str =[[NSString Alloc]initwithdata:_data encoding:nsutf8stringencoding]; NSLog (@"str =%@", str); Nsdictionary*dict =[nsjsonserialization jsonobjectwithdata:_data options:nsjsonreadingmutablecontainers Error:nil]; NSLog (@"dict =%@", Dict); Nsarray* Dicts = [Dict valueforkeypath:@"Applications"];  for(Nsdictionary *dictinchdicts) {NSLog (@"name =%@", dict[@"name"]); }}

3.JSON format description and Formatting tools

JSON is constructed in two structures:

    • A collection of name/value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), record (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative array).
    • The sequence of values (an ordered list of values). In most languages, it is understood as an array (array).

4.Json parsing

Can be done by a system-provided class nsjsonserialization, can be easily converted into a dictionary or array. The sample code is as follows.

-(void) Dealdownloadfinish: (Nlhttprequest *) request{        *dict = [nsjsonserialization JSONObjectWithData:request.data options:nsjsonreadingmutablecontainers Error:nil];         * Dicts = [dict valueforkeypath:@ "list"];      for inch dicts) {        *Event = [nlevent eventwithdictionary:dict];        [_modelarray AddObject: Event ];    }    [_tableview reloaddata];}

Network 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.