Web data download and JSON parsing for IOS development

Source: Internet
Author: User

Brief introduction

In this article, I'll show you how iOS uses nsurlconnection to download data from the Web, parse data in JSON data formats, and display data and download images asynchronously.

The knowledge points involved:

1.NSURLConnection of asynchronous download and data request method encapsulation.

2. Understanding the JSON format and JSON format for parsing use

3. Data display on the simulator and asynchronous download of pictures (using Sdwebimage to display images asynchronously, Sdwebimage is a library)

Attention:

In iOS development, both data and pictures use asynchronous download methods and cannot use synchronization.

Content

First of all, to complete a project, you need to have footage, images, and network interfaces (the network interface actually download the URL of the data URL, because your app data is requested from the server through the network)

1. Introduction to Network Download basics

(1) Mobile app Network application

Played smartphones we all know that the mobile phone app has local applications and network applications, said the popular point of local application is not required to use the network, and generally, QQ, etc. need to be online to use the network application, these Web applications need to download data online to run. Here we talk only about Web applications.

(2) Structure Program of network application

There are two kinds, one is client and one is server. The network application that needs to download data on the Internet is the client, and the service is the server that provides the data service for this network application.

(3) Common network interface mode

The common interface for iOS Web Apps is half the URL in HTTP form,

For example, the data address of the first page of the love limit application is Http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_ Id=

You can download data from this web site by using a few open source libraries (the Open Source Library) in the project. such as Afnetworking

(4) Common data formats

There are two types of data formats commonly found in iOS development, one in JSON format and the other in XML format, with relatively more JSON format

(5) General process of app interface development

iOS to develop an interface, need interface, interface material resources, network interface these three items

The process of development is generally as follows:

1. Determine the steps you want to develop, you can usually get the data first, that is, to download the data from the network interface

2. Then parse your downloaded data (JSON or XML data), create a data model, and generally use a design pattern like MVC to program the development

3. Using UI controls to display these parsed data, you will typically need to customize the cell display

2. Implementation Step 1. Use the asynchronous Download data method (nsurlconnectionasynchronous Download) encapsulates this method and can be reused later in the code .

1. First of all, the general simple state of the asynchronous download, the network interface with this as an example

Http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id=

  

[Self testnsurlconnectionasyncdownloaddata]; JSON syntax[Self Jsonformat];} -(void) jsonformat{//json//javascript Object Notation/* {"Count": "Data": [ "Zhangsan", "Lisi", "Wangwu"]} *///[] represents the array, corresponding to the Nsarray//, representing the data in parallel//{ } represents a dictionary, corresponding to the Nsdictionary//: Represents a key value pair//"Ta" represents a string, corresponding to the nsstring//20 corresponding NSNumber//json format formatting tool/Ja Son//Json Editor//Online: http://www.kjson.com/} #pragma mark-Asynchronous download-(void ) Testnsurlconnectionasyn cdownloaddata{nsstring *urlstring = @ "http://iappfree.candou.com:8080/free/applications/limited?currency=rmb& Page=1&category_id= ";//Initialize _data =  [[[Nsmutabledata alloc] init];//initiate an asynchronous URL connection request//async: After executing the method, start the download, Immediate return//download process in background (multithreaded) execution _connection = [[Nsurlconnection alloc] Initwithrequest:[nsurlrequest requestwithurl:[nsurl Urlwithstring:urlstring]] Delegate : Self startimmediately:yes]; NSLog (@ "initwithrequest execution complete" );       

When using this method, the download process is in the background of the program, follow nsurlconnectiondatadelegate This protocol can invoke the relevant methods, such as the completion of the download after the implementation of the method to complete the relevant operation

2. Here's how to do it:

  

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{    NSLog (@ " Receive the method Initwithrequest, the server responds to execution "); The data is received to execute this method, download data-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{    [_data Appenddata:data];} Data download After the completion of the method used, directly read the English meaning-(void) connectiondidfinishloading: (nsurlconnection *) connection{    nsstring *str = [[NSString alloc]initwithdata:_data encoding:nsutf8stringencoding];    NSLog (@ "Print downloaded data%@", str); Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:_data options:nsjsonreadingmutablecontainers Error: NIL]; NSLog (@ "%@", DIC); Nsarray *arr = dic[@ "Applications"]; for (nsdictionary *dic2 in arr) {NSLog (@ "name =%@", dic2[@ "name"]);} }

2. From the simple example above, we met the nsurlconnection asynchronous download, followed by an asynchronous download of the package

1. Create a class that inherits NSObject

2. Define a property to hold the data and an instance method to process the data

#import <Foundation/Foundation.h> @interface zjhttprequest:nsobject//Save the downloaded data @property (copy, nonatomic) nsmutabledata *data;//function: Incoming URL, after the download is done, execute the action method analogy button in the target object  , click on Execute Event-(void) Requestwithurl: ( NSString *) URL               target: (ID) Target               action: (SEL) action; @end    

Steps to implement a 3..M file

#import "ZJHttpRequest.h"//Remove Performselector warning #pragma clang diagnostic ignored "-warc-performselector-leaks"//class Extension/ /Project Practice://Some instance variables used internally, do not want to put in the header file, put here @interface zjhttprequest () <NSURLConnectionDataDelegate> {nsurlconnection *  _connection;    NSString *  _url;    ID  _target; SEL _action;} @end @implementation  zjhttprequest//function://Incoming URL, the download completes execution after executing the target object in the action Method-(void) Requestwithurl: (NSString * ) URL target: (ID ) target action: (SEL) action{_url =  url; _target =  target; _action =  action; /Originating URL Request _data =  [[Nsmutabledata alloc] init]; _connection = [[Nsurlconnection alloc] initwithrequest:[ Nsurlrequest Requestwithurl:[nsurl Urlwithstring:url]] delegate : Self Startimmediately:yes];} -(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData * ) data{[_data appenddata:data];} -(void) connectiondidfinishloading: (nsurlconnection * ) connection{//download Completed, execute Save method if (_target &&  [_target Respondstoselector:_action]) {[_target performselector:_action withobject:self];} @end               

4. If you do not understand the meaning of each of the code, you can look at my comments below, if there is a mistake, I very much welcome you crossing advice

  

#import "ZJHttpRequest.h"//Remove Performselector warning #pragma clang diagnostic ignored "-warc-performselector-leaks"//class Extension/ /Project Practice://Some instance variables used internally, do not want to put in the header file, placed between the @interface @end @interface zjhttprequest () <NSURLConnectionDataDelegate>{Nsurlconnection *_connection; NSString *_url; Id_target; SEL _action;} @end @implementationzjhttprequest-(void) Requestwithurl: (NSString *) URL target: (IDTarget action: (SEL) action{_url = url;//The URL of the passed parameter URL, assigned to the newly created NSString *_url object _target = target;//passed the parameter target target QFPX Viewcontroller * 0x8cea970 0x08cea970 _action = action;//passed the parameter action SEL "dealdowloadfinish:" 0x00009a4f _data =[[Nsmutabledata Alloc]init]; nsurlconnection asynchronous Download, executed this method is downloaded in the background _connection = [[Nsurlconnection alloc]initwithrequest:[nsurlrequest Requestwithurl:[nsurl Urlwithstring:url]] delegate:self startimmediately:yes];//_connection NSURLConnection * 0x8d79720 0x08d79720 Remember, this is an asynchronous download, when the program executes this method, the download data will be downloaded in the background, (multi-threaded), so after the requestwithurl is already downloading data, and then create the table, the table follows the protocol, Call those two methods, return the number of data rows, and in nsurlconnection asynchronous download, also need to follow the protocol, there will be you download the data after you can perform this method Didreceivedata//program direction is, when in Qfpxviewcontroller, When the method of this encapsulation is executed, the corresponding parameters are passed, or, in Qfpxviewcontroller, the encapsulated method is called, and then the method of encapsulation is--requestwithurl,//Then the table is created, then the data is retrieved, and the return _ Dataarray.count is here Didreceivedata,}-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//data __nscfdata * 17088 bytes 0x08d8e140 17088 bytes [_data appenddata:data];//appenddata Additional data//_data NSConcreteMut Abledata * 17088 bytes 0x08d67980 _data also got so many bytes}-(void) connectiondidfinishloading: (nsurlconnection * ) connection{//received the data, has been downloaded to complete, Then determine the target and action passed over the two parameters are not assigned to _target and _action, or _target and _action is not empty, a means of protection method, if passed over, in line with if judgment statement, then execute the method inside, That is, the logic of the program, over there Qfpxviewcontroller pass over two parameters, and then in the class Zjhttprequest encapsulated in the asynchronous download, after downloading the data to determine whether the parameters passed, if not empty the response to execute//_ Action brought over the method Dealdowloadfinish:, that is, to jump to that kind of writing method, processing data, this is the encapsulation method of a role, in fact, the asynchronous request to download data, download and then a parameter to judge, as for the data processing after downloading or "as if" In Qfpxviewcontroller, it's just a matter of writing the process logic in Qfpxviewcontroller//self zjhttprequest * 0x8c593c0 0x08c593c0//_target Qfpxviewcontroller * 0x8ce52b0 0x08ce52b0//_action SEL "dealdowloadfinish:" 0x00009a4f//_target is empty and _target can respond _ Action if (_target &&  [_target respondstoselector:_action]) {//Judging passing parameters, then carry out the method here, Execute the method Dealdowloadfinish, then jump to this method [_target performselector:_action withobject:self];// The meaning of this code is to let this class Qfpxviewcontroller execute perform this choice method _action (Dealdowloadfinish) with the Argument }} of this class self @end  

In this way, we encapsulate this method of asynchronous download, the next time directly call on it, introduce the header file, create the header file object, call the encapsulated instance method, pass the parameters, execute, and return to execute the method with the past processing data.

-(void) viewdidload {    [super viewdidload];    Additional setup after loading the view, typically from a nib.        Data interface    NSString *urlstring = @ "http://iappfree.candou.com:8080/free/applications/limited?currency=rmb& Page=1&category_id= ";        _dataarray = [[Nsmutablearray alloc] init];        Download    _request = [[Zjhttprequest alloc] init];    [_request requestwithurl:urlstring target:self Action: @selector (dealdowloadfinish:)];        [Self Createtableview];}   
-(void) viewdidload{    [Super Viewdidload];    Additional setup after loading the view, typically from a nib.    Data Interface  network interface    nsstring *urlstr = @ "HTTP://IAPPFREE.CANDOU.COM:8080/FREE/APPLICATIONS/LIMITED?CURRENCY=RMB &page=1&category_id= ";        _dataarray = [[Nsmutablearray alloc]init];                Download    _request = [[zjhttprequest alloc]init];    Self  self    qfpxviewcontroller *    0x8cea970    0x08cea970    //urlstr    __ Nscfconstantstring *    @ "http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1 &category_id= "    0x000106d4    //Call the request method of this Zjhttprequest class object, the method Requestwithurl is already class zjhttprequest encapsulated well, all, You are here self    qfpxviewcontroller * Call is to put the current target,action these two parameters and URL url into the self  zjhttprequest this class     [_ Request Requestwithurl:urlstr target:self Action: @selector (dealdowloadfinish:)];            [Self Createtabelview];        }    

Here's how to process the data dealdowloadfinish

This method is equivalent to put in viewwillappear inside, because the direction of the program is the first method below, and then return to the table returns _dataarray.count; Refresh data here Refresh-(void) Dealdowloadfinish: (zjhttprequest *) request{    nsdictionary *dic = [Nsjsonserialization jsonobjectwithdata : Request.data options:nsjsonreadingmutablecontainers Error:nil];   NSLog (@ "dic =%@", dic);    Nsarray *applist = dic[@ "Applications"];    For (Nsdictionary *dic in applist) {        Appmodel *model = [[Appmodel alloc]init];        Model.applicationid = dic[@ "ApplicationID"]; model.name = dic[@ "name"]; model.iconurl = dic[@ "IconUrl"] ; [_dataarray Addobject:model]; } [_tabelview reloaddata];}       

3. Come here and talk about the parsing of JSON data format

1. Believe that the JSON data format of the friends know, there is a Jason software is very easy to use, but also very simple

1. Get the raw data through the network interface, then select all the data and paste it into

Com+v then pops back into this window.

Then we click on the text in the upper left corner to get the JSON data we want to format well.

4. The next step is to learn the JSON data format, so that you can complete the subsequent data parsing operations
    [Self Jsonformat];} -(void) jsonformat{    //json    //javascript Object Notation/        *    {        "count": "        Data": [            "Zhangsan",            "Lisi",            "Wangwu"        ]    }    */    //[]    represents the array, corresponding to the Nsarray    //,     Represents a parallel data    //{}    representing a dictionary, corresponding    to Nsdictionary//:     denotes a key-value pair    //"Ta" for a  string, corresponding to NSString    //20    corresponding NSNumber        //json format tool    //  Jason    //  Json Editor    //  Online:/http//  www.kjson.com/    } 
5. Data acquisition, after parsing, use the custom cell to display

1. Use the stone MVC programming pattern to implement, create a basic NSObject data class and base on the UITableViewCell of the custom cell, the following is part of the code

[Self createtabelview]; }-(void) createtabelview{_tabelview =[[UITableView alloc]initwithframe:self.view.bounds Style:uitableviewstyleplain]; _tabelview.datasource =Self _tabelview.delegate =Self [Self.view Addsubview:_tabelview];} -(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{//return _dataarray.count; Back to height, return to _dataarray.count times return;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{return _ Dataarray.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{static NSString *identifer = @ "cell";//Data has 10 rows, but the judgment here shows that 7 cells are created, showing 6 Appcell *cell = [TableView Dequeuereusablecellwithidentifier:identifer]; if (cell = = Nil) {cell = [[Appcell alloc]initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:identifer] ; } Appmodel *model = _dataarray[indexpath.row];//cell.textlabel.text = model.name; cell.nameLabel.text =  Model.name; [Cell.iconimageview Setimagewithurl:[nsurl URLWITHSTRING:MODEL.ICONURL]; return cell;}           

6. Complete

7. The download of the image is implemented using the Sdwebimage method in this library.

1. Select project, point build phases, search Sdw, get all files beginning with SD

2. Full selection, double-click on the right to pop a box, enter-FNO-OBJC-ARC, use this mode

3. Then introduce the header file under the implemented class #import "Uiimageview+webcache.h"

4. Finally, this method is used to display the image loading.

  [Cell.iconimageview Setimagewithurl:[nsurl URLWITHSTRING:MODEL.ICONURL];

Summary: Implementation of a project engineering, simple interface display

I. Get interface material, network interface

Two. Get the data, parse the data

Three. Display data

where nsurlconnectionasynchronous Download and method encapsulation, as well as parsing of JSON data, are key to the implementation

Web data download and JSON parsing for IOS development

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.