After we send the request, we generally get the data, and this time we can deserialize it.
One of the commonly used data formats is JSON, which is formatted as:
{Key:value,key:value,key:value ...}
(1) Because Apple does not support JSON parsing before iOS5, many third-party parsing, Sbjson, and Jsonkit are spawned. The simple JSON deserialization example is as follows:
Nsurl *url=[nsurl urlwithstring:@ "http://www.baidu.com"]; Nsurlrequest *request=[nsurlrequest Requestwithurl:url]; [Nsurlconnection sendasynchronousrequest:request queue:[[nsoperationqueue Alloc]init] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) { nsdictionary *dict=[nsjsonserialization Jsonobjectwithdata:data options:0 Error:null]; Wpuser *user=[[wpuser Alloc]init]; The property name of the data object is preferably the key in the Dict returned in the database [user setvaluesforkeyswithdictionary:dict]; NSLog (@ "%@,%@", user.username,user.userpwd);
In the above [nsjsonserialization jsonobjectwithdata:data options:0 error:null], option is 0, which means nothing is done. Because its enumeration is 1,2,4 ... Not starting from 0:
typedef ns_options (Nsuinteger, nsjsonreadingoptions) { nsjsonreadingmutablecontainers = (1UL << 0),//root node variable C1/>nsjsonreadingmutableleaves = (1UL << 1), //Sub-node variable nsjsonreadingallowfragments = (1UL << 2) The general default is to deserialize only Nsarray and Nsdictionary} ns_enum_available (10_7, 5_0);
We test, can test with the following code, our root node is the above what type:
The test root node is what type ID dict=[nsjsonserialization jsonobjectwithdata:data options:0 error:null]; NSLog (@ "%@", dict); ID dict=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error: NULL]; NSLog (@ "%@", dict); ID dict=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:null]; NSLog (@ "%@", dict); ID dict=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments error: NULL]; NSLog (@ "%@", dict);
Typically, the company's programmers provide data types.
(2) When using Setvaluesforkeyswithdictionary, the property should use NSNumber instead of Nsinteger. The data is empty because there may be a logon failure, and so on.
(3) Nsinteger will judge the system is 64 bits with a long type, 32-bit system with the int type, so we are stitching the string, if%d, then the 64 bit under the problem, and%ld in 32 bit under the problem. The workaround is to force conversions (int), or avoid using Nsinteger.
(4) The description method will be overridden in general projects.
-(NSString *) description{ return [];}
(5) If you want to escape a special character such as a text or a space in the URL, you can also reverse the meaning
You need to escape nsstring *[email protected] "I am MT" when there are special characters such as Chinese characters or space%20 in the URL; NSString *newstr=[str stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; NSLog (@ "%@", newstr); Reverse righteousness nsstring *oldstr=[newstr stringbyremovingpercentencoding]; NSLog (@ "%@", oldstr);
Output Result:
%E6%88%91%E6%98%AF%20MT I am MT
(6) If there is an error, you can use the Connectionerror property.
If you want to update the UI, there are two ways to do this in the main thread. This error is most common and often forgets to update the UI in the main thread.
Recommendation: Use GCD as much as possible, because GCD has a lot of APIs, and Nsoperation is relatively simple.
[Nsurlconnection sendasynchronousrequest:request queue:[[nsoperationqueue Alloc]init] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {if (connectionerror) {NSLog (@ "%@", CO Nnectionerror.localizeddescription); The box is updated UI, need to be in the mainline approached//Because Nsoperation is based on GCD development, so the following gcd use completely no problem Dispatch_async (dispatch_get_main_queue (), ^{uialertview *alert=[[uialertview alloc]initwithtitle:@ "error" message:@ "error content" Delegate:self CancelButto ntitle:@ "Cancel" otherbuttontitles:@ "OK", nil]; }); Method Two: Of course you can also use Nsoperation's [[Nsoperationqueue mainqueue]addoperationwithblock:^{Uialertview *ale Rt=[[uialertview alloc]initwithtitle:@ "error" message:@ "error content" Delegate:self cancelbuttontitle:@ "Cancel" OtherButtonTitles: @ "OK", nil]; }]; }else{nsdictionary *dict=[nsjsonserialization jsonobjectwithdata:data options:0 Error:NULL]; Wpuser *user=[[wpuserAlloc]init]; The property name of the data object is preferably the key in the Dict returned in the database [user Setvaluesforkeyswithdictionary:dict]; NSLog (@ "%@,%@", user.username,user.userpwd); } }];
(7) Datawithcontentofurl is synchronous and easy to block because all network requests are preferably asynchronous
Although the following request is very convenient, there are not many steps of the URL and request, etc., but the biggest problem is that the following request is synchronous, will block NSData *imgdata=[nsdata Datawithcontentsofurl:url];
Therefore, the above method is generally used in the testing phase,The actual project is generally less used, and the network request step with request is used, so we can set the timeout length。 As below, use another request:
Nsurlrequest *request1=[nsurlrequest requestwithurl:url cachepolicy:0 timeoutinterval:10];
Apple's own caching strategy is not very good, probably because the U.S. network environment is better, so Apple does not do a lot of optimization in this area.
(8) If the user name or password is wrong, make a judgment, and then update the UI in the main thread, the box or other form prompt the user.
The judgment here can be judged with user,userid and so on, to see if there is a return data, and if there is no return data, no login is successful.
Two common data formats: XML
(1) Parsing method on the phone is generally sax (simple API for XML), it is read-only can not be modified, fast. While on the PC server The General Dom (Document Object Modal), it can be read modifiable, but slower.
(2) The specific class of sax parsing is nsamlparser.
(3) Real XML parsing is the use of several proxy methods of <NSXMLParserDelegate>, respectively, in several methods to achieve their own.
When you start parsing a document, you can initialize some data-(void) Parserdidstartdocument: (Nsxmlparser *) parser{if (!self.userarraym) {Self.userarraym =[nsmutablearray array]; }else{[Self.userarraym removeallobjects];//empty content, do not instantiate create} if (!SELF.CONTENTM) {Self.contentm=[nsmuta Blestring string]; }else{[Self.contentm setstring:@ ""];//can not use nil, with nil can be equivalent to another instantiation, here as long as the empty can}}//find that node, create a new object-(void) parser: (Nsxmlpa Rser *) Parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString * ) QName attributes: (nsdictionary *) attributedict{if ([elementname isequaltostring:@ "User"]) {Self.user=[[wpuser Alloc]init]; If there is a property, you can also set the property self.user.userid=attributedict[@ "UserId"]; }//Do not start a new node when the content should be emptied to prevent the back and forth by stitching [Self.contentm setstring:@ "];} Find the content inside that node, will be called multiple times, splicing content-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string{//stitching string [self.conte NtM appendstring:string];} End that node-(void) Parser: (Nsxmlparser *) parseR didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) qName{/* Use one of the following methods to determine if ([ElementName isequaltostring:@ "UserName"]) {SELF.USER.USERNAME=SELF.CONTENTM; }else if ([elementname isequaltostring:@ "Userpwd"]) {SELF.USER.USERPWD=SELF.CONTENTM; } ... *////Use the following KVC method if ([ElementName isequaltostring:@ "user"]) {[Self.userarraym addObject:self.user]; }else if (![ ElementName isequaltostring:@ "Users"] {[Self.user setValue:self.contentM forkey:elementname]; }}//End parsing-(void) Parserdidenddocument: (Nsxmlparser *) parser{}
Note:
(1) In iOS development, use a mutable array to assign values to the immutable group, using copy as much as possible to develop good habits:
Self.array1=[self.arraym copy];
(2) Differences between Enumerateobjectsusingblock and for and for
Detailed visibility: Enumerateobjectsusingblock, for, for (...) Differences & Performance Testing
Small details such as "IOS Development 95" JSON deserialization, XML data parsing, and UI updates in the main thread