The transmission of data on the network is common Xml,json, etc., iOS can also be used plist.
In order to transfer data, it is necessary to serialize first:
1.Serialization of. object into binary stream. (that's a word.)2.deserialization.converting a binary stream to an objectwait. (the key is to figure this out .)
JSON:(and theXMLIt's all used for data transmission.)Lightweight Data Interchange Format,is gradually replacingXML.XML:Structured Markup Language,easy to read.but the volume of data is large.
Plistoccasionally used to play:multiple formats for MAC and iOS.
first, the application scenario1.XMLthe application Scenario:xmpp--Instant Messaging,KissxmlRSSa small number of companies are currently usingOpen-Sourcewebservices, such as weather forecasts, etc.If the design is goodXMLthe interface,XMLthe parsing is not too complicated
2.JSONthe application Scenario:(small amount of data,Lightweight)Most of mobile development is still usingJSONIf you develop, or the company's background interface, it is best to useJSON.
Second, plist analytic datathe format for defining a plist is as follows:
The parsing code is as follows: (in an asynchronous thread, and finally an array)
-(void) loaddata{//1. URL Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost/videos.plist"]; 2. Request//timeOutInterval If the result is not returned from the server within 5.0, it is considered to have timed out/** nsurlrequestuseprotocolcachepolicy = 0,//using Protocol cache Policy (default) Nsurlrequestreloadignoringlocalcachedata = 1,//ignore local cache data (used when a breakpoint is resumed) Nsurlrequestreloadignoringcache Data = nsurlrequestreloadignoringlocalcachedata, = = 1//less with nsurlrequestreturncachedataelseload = 2, If there is a cache, return cached data, otherwise load Nsurlrequestreturncachedatadontload = 3,//life or death does not load remote server data, if the user does not have network connectivity can be used The following is not implemented Nsurlrequestreloadignoringlocalandremotecachedata = 4,//not implemented Nsurlrequestreloadrevalidatingcachedata = 5,//Not implemented */nsurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy:0 timeoutinterval:5.0]; 3. Network asynchronous request [Nsurlconnection sendasynchronousrequest:request Queue:[[nsoperationqueue alloc] init] completionhandler:^ ( Nsurlresponse *response, NSDATa *data, Nserror *connectionerror) {if (connectionerror) {NSLog (@ "Error%@", connectionerror); Return }//Data is a plist data, deserializing it, parsing nsarray *array = [Nspropertylistserialization Propertylistwithda Ta:data options:0 Format:null Error:null]; Refresh the data, update the UI Dispatch_async (Dispatch_get_main_queue (), ^{//...} in the UI thread; }];}
third, XML parsingXML in iOStwo ways to parse (friend pull in Android, etc.):1.SAX(Simpleapi for XML)read-only, cannot be modified, only sequential access, suitable for parsing largeXML,Fast parsing speedoften used to process large amounts of dataXML, realize the data access of heterogeneous system, realize cross-platformmove through each node from the beginning of the document to locate a specific node2.DOM(DocumentObject Model)not only can read, but also can modify, and can achieve random access, the disadvantage isSlow parsing speed, suitable for parsing small documents.Convenient Operation.generating node tree operations in memorycost-prohibitive
XMLParsing Steps:1.instantiation ofNsxmlparser,Incomingreceived from the serverXMLData2.Defining the parserAgent3.Parserparsing,completed by resolving proxy methodXMLparsing of data.
parsingXMLuse of theProxy Method:
1. start parsing XML documents
-(void)parserdidstartdocument:
2. Start parsing an element, traversing the entire XML, identifying the element node name, such as <video> start
-(void) parser:didstartelement: namespaceURI:qualifiedName:attributes:
3. text node, get the information data stored in the text node . Data in a node <video>XXXX</video>
-(void) parser:foundcharacters:
4. End a node such as </video> start
-(void) parser:didendelement: namespaceuri:qualifiedname:
Note: During the parsing process, 2 , 3 , 4 three methods are repeated until the traversal is complete.
5 . parsing XML End of document
-(void) Parserdidenddocument:
6 . Parse Error
-(void) Parser:parseerroroccurred:
Note: FromNetworkThe Loading data iscan't load with lazyOf.
The XML file format is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><videos><video videoid= "1" ><name> Cang teacher 1</name> <length>320</length><videourl>/teacher 1.mp4</videourl><imageurl>/Cang teacher 1.png</ Imageurl><desc> Learn iOS find Cang teacher 1</desc><teacher> Cang teacher 111</teacher></video><video Videoid= "2" ><name> Cang teacher 2</name><length>2708</length><videourl>/teacher 2.mp4</ videourl><imageurl>/Cang Teacher 2.png</imageurl><desc> Learn iOS to find Cang teacher 2</desc><teacher> Cang Teacher 222 </teacher></video></videos>
The parsing code is as follows:
/** load Data */-(void) loaddata{//1. URL determine resource Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost/videos.xml"]; 2. Request to set up requests nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; 3. Send an asynchronous request, create a new data processing queue, and then update the UI after data processing is complete [nsurlconnection sendasynchronousrequest:request Queue:[[nsoperationqueue alloc] Init] completionhandler:^ (nsurlresponse *response, NSData *data, Nserror *connectionerror) {//1> instantiate XM L parser Nsxmlparser *parser = [[Nsxmlparser alloc] initwithdata:data]; 2> Set Parser proxy parser.delegate = self; 3> begins to parse [parser parse]; }];} #pragma mark-xml resolution Proxy method//1. Start parsing Document-(void) Parserdidstartdocument: (Nsxmlparser *) parser{//To avoid repeating the data refresh, you can empty the array [self.videolist removeallobjects];} 2,3,4 three methods will be called//2 in a loop. Start an Element (node) <xxx>-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: ( NSString *) NamespaceURI qualifiedname: (NSString *) QName AttriButes: (nsdictionary *) attributedict{if ([ElementName isequaltostring:@ "video"]) {//Create new Video Object Self.cu Rrentvideo = [[Video alloc] init]; Use KVC to assign values [Self.currentvideo setvalue:attributedict[@ "VideoID"] forkeypath:@ "videoid"]; }//Before starting the 3rd method, empty the string contents [Self.elementm setstring:@ "];} 3. Found character (node middle content)-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string{[Self.elementm appendString: string];} 4. End node </xxx>-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) qname{if ([ElementName isequaltostring:@ "video"]) {//Add the node currently being resolved to the array [Self.videolist AddObject:self.currentVideo]; } else if (![ ElementName isequaltostring:@ "Videos"]) {[Self.currentvideo SetValue:self.elementM forkeypath:elementname]; }}//5. End document Resolution-(void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@ "End document parsing%@", self.videolist); NSLog (@ "%@", [Nsthread CurrentThread]); Dispatch_async (Dispatch_get_main_queue (), ^{//ui thread Refresh UI ...});} 6. When processing network data, do not forget error handling-(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror{NSLog (@ "Error%@", ParseError);}
Iv. JSON parsingThe parsed data needs to be deserialized in the following way: [Nsjsonserialization
Jsonobjectwithdata:d ata options:0 Error:null];
JSON parsing is convenient, and lightweight, especially for mobile phones, save traffic, fast. The JSON format data is as follows:
[{"VideoID": "1", "name": "Cang Teacher 1", "Length": "The", "Videourl": "/Cang teacher 1.mp4", "ImageURL": "/Cang teacher 1.png", "desc": "Learn iOS find Cang Teacher 1 "," Teacher ":" Cang Teacher 111 "},{" VideoID ":" 2 "," Name ":" Cang Teacher 2 "," Length ":" 2708 "," Videourl ":" \/Cang teacher 2.mp4 "," ImageURL ":" \ \ Cang teacher 2.png "," desc ":" Learn iOS to find Cang teacher 2 "," Teacher ":" Teacher Cang 222 "}]
The parsing code is as follows:
-(void) loaddata{ //1. URL nsurl *url = [Nsurl urlwithstring:@ "Http://localhost/videos.json"]; 2. Request Nsurlrequest *request = [Nsurlrequest requestwithurl:url]; 3. Send asynchronous Request [nsurlconnection sendasynchronousrequest:request Queue:[[nsoperationqueue alloc] init] Completionhandler : ^ (nsurlresponse *response, NSData *data, Nserror *connectionerror) { //data is a JSON data //deserialization of data, parsing Nsarray *array = [nsjsonserialization jsonobjectwithdata:data options:0 error:null]; Refresh data, update UI Dispatch_async (Dispatch_get_main_queue (), ^{ //Update UI in main thread ... });} ];}
Reprint Please specify source:http://blog.csdn.net/xn4545945