iOS Network Programming Learning

Source: Internet
Author: User
Tags xml parser

Network access to get data
Define a UIWebView attribute to display data @property (strong, nonatomic) Iboutlet UIWebView *mywebview;//.......// Use Nsurlconnection to send asynchronous requests for data-(void) GetData: (ID) sender{//visited website address nsstring *str = @ "http://www.apple.com/"; Instantiate Nsurl object Nsurl *url = [Nsurl urlwithstring:str]; Instantiate Nsurlrequest object Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Instantiation of the operation queue Nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; Send asynchronous request [Nsurlconnection sendasynchronousrequest:request queue:queue Completionhandler: ^ (Nsurlresponse *response, NSData *data, Nserror *error) {//Get network Fetch data if ([data length] > 0 && error = = nil) { Convert NSData to nsstring nsstring *html = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; Use UIWebView to display Web pages [Self.mywebview loadhtmlstring:html Baseurl:nil]; NSLog (@ "html =%@", html); } }];} /* When using nsurlconnection to send synchronization requests to get data using synchronous requests, it's best to do it in a separate thread,This prevents the program from blocking */-(void) Getdatatwo: (ID) sender{//global queue dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue _priority_default, 0); Asynchronous parallel queue, opens up a new thread Dispatch_async (queue, ^{nsurl *url = [Nsurl urlwithstring:@ "http://www.apple.com"]; Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Nsurlresponse *response; Nserror *error; Nsurlconnection send sync request, get data nsdata *data = [Nsurlconnection sendsynchronousrequest:request returningresponse:& Response error:&error]; Judgment result if ([data length] > 0 && error = = nil) {NSString *html = [[NSString alloc] Initwithdat A:data encoding:nsutf8stringencoding]; NSLog (@ "html =%@", html); } });}

/** * Use Nsmutableurlrequest to send a POST request to the server for data */-(void) Getdatathree: (ID) sender{//Create a thread dispatch_queue_t queue = di    Spatch_get_global_queue (dispatch_queue_priority_default, 0); Perform asynchronous task Dispatch_async (queue, ^{//Get Sina's weather information URL//http://php.weather.sina.com.cn/xml.php?city=%b1%b1%be% A9&password=djoyniet8234jlsk&day=0//Get data from the network in block nsstring *str = @ "Http://php.weather.sin        A.com.cn/xml.php ";        Create Nsurl object Nsurl *url = [Nsurl urlwithstring:str];        Variable URL request nsmutableurlrequest *mrequest = [[Nsmutableurlrequest alloc] init];        Set the URL for the request [Mrequest Seturl:url];        Set request time-out [mrequest settimeoutinterval:10];        Set the request method to post [Mrequest sethttpmethod:@ "POST"];        Body content NSString *body = @ "city=%b1%b1%be%a9&password=djoyniet8234jlsk&day=0";                Set body [Mrequest sethttpbody:[body datausingencoding:nsutf8stringencoding];        Get a responseNsurlresponse *response;        Nserror *error; Get Return data NSData *data = [nsurlconnection sendsynchronousrequest:mrequest returningresponse:&response Error:&amp        ; error];                Convert NSData to string nsstring *content = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];        Load data using UIWebView [Self.mywebview loadhtmlstring:content Baseurl:nil];            Output result NSLog (@ "content =%@", content); });}

  

Data parsing

In network programming, the data format obtained from the server is broadly divided into two types: JSON and XML. JSON, as a lightweight data interchange format, is gradually replacing XML as a common format for network data.

Test the following: Call a weather forecast API, address is: http://m.weather.com.cn/data/101010100.html

/** * Parse JSON data access http://m.weather.com.cn/data/101010100.html using the system's own library nsjsonserialization, and return the result as: {"Weatherinfo": {" City ":" Beijing "," city_en ":" Beijing "," date_y ":" March 4, 2014 "," date ":" "," Week ":" Tuesday "," Fchh ":" One "," Cityid ":" 101010100 "," Temp1 ":" 8℃~-3℃ "," Temp2 ":" 8℃~-3℃ "," Temp3 ":" 7℃~-3℃ "," Temp4 ":" 8℃~-1℃ "," TEMP5 ":" 10℃~1℃ "," TEMP6 ":" 10℃~2℃ "," tempF1 ": "46.4℉~26.6℉", "tempF2": "46.4℉~26.6℉", "tempF3": "44.6℉~26.6℉", "tempF4": "46.4℉~30.2℉", "tempF5": "50℉~33.8℉", " TempF6 ":" 50℉~35.6℉ "," Weather1 ":" Sunny "," weather2 ":" Sunny "," Weather3 ":" Sunny "," weather4 ":" Cloudy "," Weather5 ":" Cloudy "," WEATHER6 ": "Cloudy", "IMG1": "0", "img2": "The", "IMG3": "0", "img4": "", "Img5": "0", "img6": "The", "Img7": "0", "Img8": "1", "IMG9": "1", " Img10 ":" "img11": "1", "Img12": "The", "Img_single": "0", "img_title1": "Sunny", "img_title2": "Sunny", "img_title3": "Sunny", "img_ Title4 ":" Clear "," img_title5 ":" Clear "," Img_title6 ":" Sunny "," Img_title7 ":" Sunny "," Img_title8 ":" Cloudy "," Img_title9 ":" Cloudy "," img_ Title10 ":" Cloudy "," Img_title11 ":" Cloudy "," img_title12 ":" Cloudy "," Img_title_single ":" Sunny "," Wind1 ":" North wind 4-5-Turn Breeze "," wind2 ":" Breeze "," Wind3 ":" Breeze "," Wind4 ": "Breeze", "Wind5": "Breeze", "Wind6": "Breeze", "fx1": "North Wind", "FX2": "Breeze", "FL1": "Level 4-5 to less than 3", "FL2": "Less than 3 levels", "FL3": "Less than 3", "FL4": "Less than 3" , "FL5": "Less than 3 levels", "fl6": "Less than 3 levels", "Index": "Cold", "index_d": "The cold weather, recommended thick down jacket, fur coats thicker sweater, such as winter clothing." In particular, the elderly should pay attention to warm frost. "," index48 ":" Cold "," index48_d ":" Cold weather, recommended cotton clothes, down jacket, leather jackets and sweaters and other winter clothing. " The frail and infirm are suitable for thick coat, winter coat or thick down jacket. "," Index_uv ":" Medium "," INDEX48_UV ":" moderate "," INDEX_XC ":" More Appropriate "," INDEX_TR ":" General "," Index_co ":" More Comfortable "," st1 ":" 7 "," St2 ":" 3 "," ST3 ":" 8 "," St4 ":" 0 "," st5 ":" 7 "," St6 ":" 1 "," INDEX_CL ":" Less suitable "," Index_ls ":" Basic Fit "," Index_ag ":" Easy Hair "}} */-(void)    Getweatherdata: (ID) sender{Nsurl *url = [Nsurl urlwithstring:@ "http://m.weather.com.cn/data/101010100.html"];        Nsurlrequest *requst = [Nsurlrequest Requestwithurl:url]; Send asynchronous request [Nsurlconnection sendasynchronousrequest:requst Queue:[[nsoperationqueue alloc] init] completionhandler:^ (             Nsurlresponse *response, NSData *data, Nserror *error) {if ([data length] > 0 && error = = nil) { Convert NSData to nsdictionary nsdictionary *dic = [nsjsonserializationJsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil];            The result is a dictionary in the dictionary, which obtains the dictionary of key weatherinfo nsdictionary *dic2 = [dic objectforkey:@ "Weatherinfo"];            Traverse dictionary for (NSString *key in Dic2) {NSLog (@ "%@:%@", Key, [Dic2 Objectforkey:key]); }        }    }];}

  

XML parsing can be done through Apple's own API, Nsxmlparser, and its proxy class nsxmlparserdelegate.

There is a set of methods in the Nsxmlparsedelegate proxy class to detect the read state of a document, for example, document start, document end, element start, element end, content start, etc.

The basic idea of parsing XML data is to create an empty object at the beginning of the element, read the content and assign a value to the object's properties when the content is found, and add the object to the collection at the end of the element.

Example code:

Create a Customer class @interface Customer:nsobject@property (nonatomic, assign) int cid;  Customer Id@property (nonatomic, retain) nsstring *name;//customer Name @property (nonatomic, assign) int age;  Customer Age @end

  

First define 4 attributes @property (nonatomic, retain) Customer *customer;  Customer Instance @property (Nonatomic, retain) Nsxmlparser *parser;    XML Parser @property (nonatomic, retain) Nsmutablearray *array;    Variable group @property (nonatomic, strong) NSString *currrentelement;    Current element//initialization Method-(void) initparser{//Initialize an array to hold the client object self.array = [Nsmutablearray arraywithcapacity:10];    Get the URL path to the client XML file NSString *str = [[NSBundle Mainbundle] pathforresource:@ "Customers" oftype:@ "xml"];    Convert customer XML to nsdata nsdata *data = [[NSData alloc] initwithcontentsoffile:str];    Instantiate XML Parser self.parser = [[Nsxmlparser alloc] initwithdata:data]; Set proxy self.parser.delegate = self;} /** * Implement protocol Proxy method *///read document Start-(void) Parserdidstartdocument: (Nsxmlparser *) parser{NSLog (@ "parserdidstartdocument ...");} Read document end-(void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@ "parserdidenddocument ...."); Read element start-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceurI qualifiedname: (NSString *) QName attributes: (nsdictionary *) attributedict{NSLog (@ "didstartelement ...");    Self.currrentelement = elementname;    if ([Self.currrentelement isequaltostring:@ "Customer"]) {self.customer = [[Customer alloc] init];        }}//found Content-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string{NSLog (@ "foundcharacters ...");        if ([self.currrentelement isequaltostring:@ "id"]) {int CID = [string IntegerValue];    [Self.customer Setcid:cid];    } else if ([self.currrentelement isequaltostring:@ "name"]) {[Self.customer setname:string];    } else if ([Self.currrentelement isequaltostring:@ "Age"]) {[Self.customer setage:[string IntegerValue]]; }}//read element end-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *)        NamespaceURI qualifiedname: (NSString *) qname{NSLog (@ "didendelement ..."); if ([ElementName isequaltostring:@ "Customer"]) {[Self.array AddobjeCt:self.customer]; } self.currrentelement = nil;}    Start parsing Method-(void) Parse: (ID) sender{//Delete all data in array [Self.array removeallobjects];    Start parsing [Self.parser parse]; Get the array size nsinteger count = [Self.array count];}

  

 

iOS Network Programming Learning

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.