The Cloud app for iOS

Source: Internet
Author: User

10.1 GET Request

10.2 XML parsing

10.3 JSON parsing

10.4 POST Request

10.1 GET Request

Query IP attribution via a third-party provided cloud service: http://www.youdao.com/smartresult-xml/search.s?type=ip&q=218.241.121.186

Its return format is XML:

A new example: Cssimplexml, design prototype:

Edit Button Event:

-(ibaction) query: (ID) Sender {    nsstring* strurl = [NSString stringwithformat:@ "http://www.youdao.com/ smartresult-xml/search.s?type=ip&q=%@ ", Iptext.text];    nsurl* url = [Nsurl Urlwithstring:strurl];        nsurlrequest* request = [[Nsurlrequest alloc]initwithurl:url];        nsurlconnection* connection = [[Nsurlconnection alloc]initwithrequest:request delegate:self];        [Connection release];    [Request release];    [Activityindicator startanimating];}

To define a delegate for Nsurlconnection:

Nsurlrequest *request = [[Nsurlrequest alloc] initwithurl:url];

Nsurlconnection *connection = [[Nsurlconnection alloc] initwithrequest:request delegate:self];

A delegate (delegate) is an event-handling mechanism that fires when a condition is met. The delegate:self description is to delegate the current object handling events, and we need to implement their callback methods.

Nsurlconnection callback method

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data request was successful and received. -(void) connection: (Nsurlconnection *) connection  didfailwitherror: (nserror *) Error  request succeeded, but loading data was unexpected. -(void) connectiondidfinishloading: (nsurlconnection*) connection load data successfully, executed after the Connection:didreceivedata method.

Receive data processing

-(void) connection: (nsurlconnection*) connection didreceivedata: (NSData *) data {    //default support for Chinese is not good    Nsstringencoding enc = cfstringconvertencodingtonsstringencoding (kcfstringencodinggb_18030_2000);    nsstring* gbknsstring = [[NSString alloc]initwithdata:data Encoding:enc];    If it is black UTF-8 Nsxmlparese will error    xmlstring = [[NSString alloc]initwithstring:[gbknsstring stringbyreplacingoccurrencesofstring:@ "<?xml version=\" 1.0\ "encoding=\" Gbk\ "?>" withString:@ "<?xml Version=\ "1.0\" encoding=\ "utf-8\"?> "]";    NSLog (@ "%@", xmlstring);    [Gbknsstring release];}

The XML parsing class provided by the IPhone SDK can only parse the UTF-8 encoding, if the XML encoding returned from the server is GBK, and so on, to convert to Utf-8 and start parsing.

10.2 XML parsing

About the iphone sending get requests is implemented through the Nsurlrequest and nsurlconnection two classes.

In a multitude of callback methods. Parsing XML begins with the Connectiondidfinishloading: method.

Parsing an XML file is also done by means of an XML callback.

Nsxmlparser, is the iphone Parsing XML SDK tool class.

Nsxmlparser is parsed using sax rather than DOM, and Sax is based on event-triggered parsing, where the parser traverses the XML document from top to bottom, encountering start tags, closing tags, document start, document end, and string triggering events.

Parsing begins processing

-(void) connectiondidfinishloading: (nsurlconnection*) connection {    [activityindicator stopanimating];    Start parsing xml    nsxmlparser* ipparser = [[Nsxmlparser alloc]initwithdata:[xmlstring datausingencoding: Nsutf8stringencoding]];;    Ipparser.delegate = self;    [Ipparser parse];    [Ipparser release];}

Nsxmlparser callback method

-(void) Parserdidstartdocument: (Nsxmlparser *) parser trigger at start of document-(void) Parser: (Nsxmlparser *) parser Parseerroroccurred: (Nserror *) parseerror  document error when triggering-(void) Parser: (Nsxmlparser *) Parser didstartelement: ( NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) QualifiedName attributes: ( Nsdictionary *) Attributedict hit a start tag when triggered. -(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string trigger-(void) Parser: (Nsxmlparser *) parser Didendelement: (NSString *) Elementnamenamespaceuri: (NSString *) Namespaceuriqualifiedname: (NSString *) qName Start when the end tag is encountered. -(void) Parserdidenddocument: (Nsxmlparser *) parser  triggered at the end of the document.

callback method for document start

This method is only dispatched once during the parsing process, and in this method the initialization of parsing is usually done.

Trigger at start of document-(void) Parserdidstartdocument: (Nsxmlparser *) Parser {    info = [[Nsmutabledictionary alloc] INITWITHCAPACITY:1];}

Document Error callback method

Trigger on document Error-(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror {    uialertview* Erroralert = [[Uialertview alloc]initwithtitle:[parseerror localizeddescription] Message:[parseerror Localizedfailurereason] Delegate:nil cancelbuttontitle:@ "OK" otherbuttontitles:nil];    [Erroralert show];    [Erroralert release];}

Encounter start Tag callback method

The parameter elementname is the name of the label, Attributedict is the attribute list, NamespaceURI is the namespace, and if there is a namespace qualifiedname is the specified prefix name.

Triggered when a start tag is encountered. -(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QualifiedName attributes: (nsdictionary *) attributedict {    NSLog (@ "value:%@\n", elementname);    Currenttagname = elementname;}

Encountered string callback method

Triggered when a string is encountered-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string {    NSLog (@ "value:%@\n", string );    string = [string stringbyreplacingoccurrencesofstring:@ "\ n" withstring:@ ""];    if ([currenttagname isequaltostring:@ "IP"]) {        if (![ String isequaltostring:@ ""]) {            [info setvalue:string forkey:currenttagname];        }     } else if ([ Currenttagname isequaltostring:@ "Location"]) {        if (![ String isequaltostring:@ ""]) {            [info setvalue:string forkey:currenttagname];}}    

End tag callback method encountered

Start when the end tag is encountered. -(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) Elementnamenamespaceuri: (NSString *) Namespaceuriqualifiedname: (NSString *) QName {}

End Document callback method encountered

Triggered at the end of a document encounter. -(void) Parserdidenddocument: (Nsxmlparser *) parser  {    nsmutablestring* outstring = [[Nsmutablestring alloc] INITWITHCAPACITY:1];    For (ID key in info) {        [outstring appendformat:@ "%@:%@\n", key, [info Objectforkey:key]];    }    Msgtext.text = outstring;    [outstring release];    [XMLString release];}

10.3 JSON parsing

Http://www.geonames.org/export/ws-overview.html

Get JSON:

{    status =     {        message = "The daily limit of 30000 credits demo has been exceeded. Throttle your requests or use the commercial service. ";        Value =;    };}
10.3.1 JSON parsing API

The IPhone SDK does not provide a JSON parsing API and can use the third-party API class library Json-framework:

https://github.com/stig/json-framework/

Copy the class below classes/json/to the classes directory of our project and right-click to add the existing class file.

Implementing a callback method

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data-(void) Connectiondidfinishloading: ( nsurlconnection*) connection-(void) connection: (Nsurlconnection *) connection  

Connection:didreceivedata:

-(void) connection: (nsurlconnection*) connection didreceivedata: (NSData *) data {    outstring = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];    NSLog (@ "%@", outstring);}

Connectiondidfinishloading:

Outstring's Jsonvalue message gets the NSString classification (catelog) provided in the Nsmutabledictionary,json API

-(void) connectiondidfinishloading: (nsurlconnection*) connection {    nsmutabledictionary* jsonobj = [outstring Jsonvalue];    NSLog (@ "%@", jsonobj);    nsmutabledictionary* jsonsubobj = [jsonobj objectforkey:@ "status"];        nsstring* text = [[NSString alloc]initwithformat:@ "message=%@\n\nvalue=%@", [jsonsubobj objectforkey:@ "message"],[ Jsonsubobj objectforkey:@ "value"];    Msttext.text = text;    [Text release];    [outstring release];    [Activity stopanimating];}

Document Error callback method

-(void) connection: (Nsurlconnection *) connection  didfailwitherror: (nserror *) Error {    
Delegate:nil cancelbuttontitle:@ "OK" otherbuttontitles:nil]; [Erroralert show]; [Erroralert release];}

Click Button Events

-(Ibaction) go: (ID) sender{    nsstring *strurl [email protected] "Http://api.geonames.org/findNearByWeatherJSON?  Lat=43&lng=-2&username=demo ";  Nsurl *url = [Nsurl Urlwithstring:strurl];  Nsurlrequest *request = [[Nsurlrequest Alloc]initwithurl:url];  Nsurlconnection *connection = [[Nsurlconnection alloc]initwithrequest:request delegate:self];  [Connection release];  [Request release]; [Activityindicatorview startanimating];}
10.4 POST Request

To learn about the iphone's post request, the following scenarios are arranged:

Enter the user name and password in the screen, and then submit the data to the server side by post.

Nsmutableurlrequest

The POST request differs from GET, not using the nsurlrequest, but using the Nsmutableurlrequest class, which is a mutable nsurlrequest class.

-(ibaction) Login: (ID) Sender {    //http://www.sunnyer.com/shop/member!login.action    //member.email:[email Protected]    //MEMBER.PASSWORD:DFGDFGRF    [Activity startanimating];    nsstring* post = [NSString stringwithformat:@ "memberidorcellphoneoremail=%@&&password=%@", Username.text, Password.text];    nsdata* postdata = [post datausingencoding:nsutf8stringencoding];    nsurl* Postservierurl = [Nsurl urlwithstring:@ "Http://www.jinjiang.com/membercenter/member/ordinaryLogin"];    nsmutableurlrequest* request = [Nsmutableurlrequest Requestwithurl:postservierurl];    [Request sethttpmethod:@ "POST"];    [Request Sethttpbody:postdata];    nsurlconnection* connection = [[Nsurlconnection alloc] initwithrequest:request delegate:self];    if (!connection) {        NSLog (@ "Failed to submit Request"),    } else {        NSLog (@ "Request submitted");    }    [Connection release];}

The post parameter is passed as a string: memberidorcellphoneoremail=%@&&password=%@

[Request sethttpmethod:@ "POST"];

Know the request method is the Post method, but be aware that the post must be capitalized.

[Request Sethttpbody:postdata]; The statement is the data that will be submitted in the request body.

Connection:didreceivedata:

-(void) connection: (nsurlconnection*) connection didreceivedata: (NSData *) data {    outstring = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];    NSLog (@ "%@", outstring);}

Connectiondidfinishloading:

-(void) connectiondidfinishloading: (nsurlconnection*) connection{    NSLog (@ "%@", outstring);    [WebView loadhtmlstring:outstring baseurl:[[nsurl alloc]initwithstring:@ "http://www.jinjiang.com"];    [Activity stopanimating];}

Document Error callback method

-(void) connection: (Nsurlconnection *) connection  didfailwitherror: (nserror *) error {    uialertview* Erroralert = [[Uialertview alloc]initwithtitle:[error localizeddescription] Message:[error LocalizedFailureReason]
Delegate:nil cancelbuttontitle:@ "OK" otherbuttontitles:nil];
[Erroralert show];
[Erroralert release];
}

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.