iOS network data download and JSON parsing
Brief introduction
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
Knowledge 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 Network Download basics
(1) What is a Web application?
In general, the iphone computer, the camera does not need to download data from the network can also run, so this type of application is a local application, but the vast majority of applications on the iphone need a network to run, such as QQ, shrimp music, So in iOS development, you need to know how to download data from the Web.
(2) Program Structure of network application
Network application is different from local application, network application data is downloaded from the network, so need to run a program on the network to provide data for the application, or provide services, then this network application is generally called the client, and the service running on the network is called the server
(3) Common form of network interface
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
(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 interface development
Developing an interface in iOS that requires interfaces, interface assets, and network interfaces
The process of development is generally as follows
1, download data
2, parsing JSON or XML data, creating a data model
3, use the control to display data, when necessary to customize the view, such as custom cell
2.NSURLConnection use
NSString sync Download
[Self testnsstringdownloaddata];
-(void) testnsstringdownloaddata{//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)NSString*urlstring =@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id="; //Download Data//generating Nsurl objects from addressesNserror *error =Nil; Nsurl*url =[Nsurl urlwithstring:urlstring]; NSString*content = [[NSString alloc] Initwithcontentsofurl:url encoding:nsutf8stringencoding error:&ERROR]; if(error==Nil) {NSLog (@"content =%@", content); } Else{NSLog (@"Download Failed"); } //How to use the project//1. Synchronous download, Initwithcontentsofurl will not be returned until download is finished//causes the interface to feign death, cannot use//2. Using asynchronous Download (nsurlconnection asynchronous download) }
nsurlconnection sync Download
[Self testnsurlconnectionsyncdownloaddata];
-(void) testnsurlconnectionsyncdownloaddata{NSString*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"); } }
Nsurlconnection Asynchronous Download
[self testnsurlconnectionasyncdownloaddata];
-(void) testnsurlconnectionasyncdownloaddata{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); //simplest: Show all app names//parsing JSON//function: JSON data converted to Nsarray or nsdictionaryNsdictionary *dict =[nsjsonserialization jsonobjectwithdata:_data options:nsjsonreadingmutablecontainers Error:nil]; //NSLog (@ "dict =%@", dict); //Nsarray *applist = dict[@ "Applications"];Nsarray *applist = [Dict valueforkey:@"Applications"]; for(Nsdictionary *appdictinchapplist) {NSLog (@"name =%@", appdict[@"name"]); } //Nsarray *a = @[@ "Test" @ "VEC"]; //nsdictionary *d = @{@ "K1": @ "v1" @ "K2": @ "v2"}; //NSLog (@ "v =%@", d[@ "K1"]); }-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"error =%@", error);}
3.JSON format description and Formatting tools
JSON Syntax
[self jsonformat];
-(void) Jsonformat
{
Json
JavaScript Object Notation
/*
{
"Count": 20,
"Data": [
"Zhangsan",
"Lisi",
"Wangwu"
]
}
*/
[] represents the array, corresponding to the Nsarray
That represents the data that is tied
{} represents the dictionary, corresponding to the Nsdictionary
: represents a key-value pair
"Ta" means string, corresponding to NSString
corresponding NSNumber
JSON Format Formatting tool
Jason
Json Editor
// online : http://www.kjson.com/
}
4. A completed implementation (includes creation of model, use of sdwebimage)
:
iOS network data download and JSON parsing