iOS Web data download and JSON parsing
Brief introduction
In the development of iOS, the application type can be broadly divided into two categories, one is the local application, the general use of local data loading content, the second is the network application, using the service side of the transmission of data after the analysis of loading content, the following will introduce the basic knowledge of network application development. The following points will be covered:
1. Use Nsurl and other classes for data download;
2.JSON data format and JSON parsing;
3. Use third-party library sdwebimage to display images.
First, Nsurl Class 1, Nsurl related class introduction
(1) Nsurl: Request Address
(2) Nsurlrequest: Encapsulates a request address to save all data sent to the server
(3) Subclass of Nsmutableurlrequest:nsurlrequest
(4) Nsurlconnection: Responsible for sending the request to establish a connection between the client and the server. Send nsurlrequest data to the server and collect response data from the server
2, Nsurl related class use
(1) Create a Nsurl object, set the request path (set the request path)
(2) Incoming Nsurl Create a Nsurlrequest object, set the request header and the request body (Create request object)
(3) Send nsurlrequest using nsurlconnection (send request)
3, the use of relevant
Nsurl can be used to establish a synchronous request or asynchronous request, the synchronization request will keep the application waiting for the server to return data state, if the server, no return data, then the main thread UI will be stuck can not continue to perform operations, into the so-called suspended animation, asynchronous request can avoid this situation;
(1) Sync request
Reiterate the steps to send the request
1. Set the request path
2. Create a Request object
3. Send the request below is the sample code
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"); }
Here http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1&category_id= is the network interface, Generate requests and establish connections through this network interface
(2) Asynchronous request
There are two ways to implement asynchronous requests, one is to take advantage of block callbacks of blocks, and the other is to use proxy protocols, which simply introduce the callback of a block of code.
Asynchronous request for block block of code:
Sample code
Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://iappfree.candou.com : 8080/free/applications/limited?currency=rmb&page=1&category_id="]]; *mainqueue = [Nsoperationqueue mainqueue]; // get the main thread [Nsurlconnection sendasynchronousrequest:request queue:mainqueue completionhandler:^ (NSURLResponse *response, NSData *data, Nserror *connectionerror) { }];
Using sendasynchronousrequest:queue:completionhandler:^ (Nsurlresponse *response, NSData *data, NSError *connectionError The {} method sends an asynchronous request, and the contents of the code block are generally parsed by the downloaded data and then refreshed by the UI interface, because the UI refresh must be done in the main thread, so the main operation queue is created to refresh;
Proxy protocol Asynchronous Request:
Sample code
-(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); }-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"error =%@", error);}
It is necessary to abide by the Nsurlconnectiondatadelegate protocol before establishing the connection, the Nsurl related class is easy to use, follow the specified steps.
Second, JSON-related 1, JSON basic knowledge
The data returned to the app by the server typically has two formats, one in JSON format and the other in XML format, which is described in JSON format.
The JSON data format is fairly concise and lightweight, so it's easy to parse, and here's a sample code for JSON
{"Applications": [{"ApplicationID": "455680974", "slug": "rhythm-repeat", "name": "\u8282\u594f\u91c d\u590d "," ReleaseDate ":" 2014-07-01 "," Version ":" 2.3 "," description ":" \u754c\u9762\u6e05\u65b0\u7b80\u53 55\u7684\u97f3\u4e50\u8282\u594f\u6e38\u620f\u3002\u6e38\u620f\u7684\u64cd\u4f5c\u975e\u5e38\u7b80\u5355\uff0c \u53ea\u9700\u6839\u636e\u63d0\u793a\u4f9d\u6b21\u70b9\u51fb\u76f8\u5e94\u7684\u56fe\u6807\u5373\u53ef\uff0c\ U5171\u6709\u4e09\u79cd\u4e50\u66f2\u9009\u62e9\u3002 "," categoryId ": 6014," CategoryName ":" Game "," Iconur L ":" Http:\/\/photo.candou.com\/i\/114\/55b07f3725eae8b3cafc9bce10d16e46 "," Itunesurl ":" http:\/\/ Itunes.apple.com\/cn\/app\/rhythm-repeat\/id455680974?mt=8 "," Starcurrent ":" 4.0 "," Staroverall ":" 4.0 "," R Atingoverall ":" 0 "," Downloads ":" 3217 "," Currentprice ":" 0 "," Lastprice ":" A "," pricetrend ":" Limite D "," Expiredatetime ":" 2015-04-06 01:50:41.0 "," ReleasenotEs ":" Multi-Touch bug fixed "," Updatedate ":" 2014-10-17 15:45:27 "," fileSize ":" 16.69 "," IPA ":" 1 "," s Hares ":" 390 "," Favorites ":" 273 "},
Parsing JSON will convert JSON to OC data type
Curly braces {} correspond to nsdictionary in OC, brackets [] correspond to Nsarray in OC, "" double quotes correspond to nsstring,6014 in OC for NSNumber in OC
2. JSON parsing
In iOS, there are a number of common parsing scenarios for JSON:
(1) Third-party framework: Jsonkit, Sbjson, Touchjson
(2) Apple native (comes with): Nsjsonserialization
The following describes the use of nsjsonserialization
Common methods of Nsjsonserialization
(1) JSON data-"OC Object"
+ (ID) jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (NSERROR *) error;
When the outside of the JSON data is {}, the return type is set to Nsdictionary, and the return type is nsarray when [];
Where data is accepted from the server;
(2) OC Object-"JSON data"
+ (NSData *) Datawithjsonobject: (ID) obj options: (nsjsonwritingoptions) opt error: (NSERROR *) error;
Sample code
- (void) Dealdownload: (Myhttprequest *) request{nsdictionary*dict =[nsjsonserialization JSONObjectWithData:request.data options:nsjsonreadingmutablecontainers Error:nil]; Nsarray*arrtemp = dict[@"Applications"]; [_dataarray removeallobjects]; for(Nsdictionary *dictempincharrtemp) {Appdatamodel*modal =[[Appdatamodel alloc] init]; Modal.applicationid= dictemp[@"ApplicationID"]; Modal.iconurl= dictemp[@"ICONURL"]; Modal.name= dictemp[@"name"]; [_dataarray Addobject:modal]; } [_tableview reloaddata];}
JSON is simple to parse, not a lot to repeat here
Third, the use of sdwebimage
The third library sdwebimage does not support arc, so it needs to be configured before use, set-fno-objc-arc for all files in the library,
Using the method Setimagewithurl in the library, passing in a picture URL can be loaded when the picture needs to be displayed
Iv. Summary
The knowledge involved in this article is not difficult to understand, more practice is good, and my current level is limited, if there are errors, but also please comment in the following points, thank you!
iOS Web data download and JSON parsing