IOS之雲端應用

來源:互聯網
上載者:User

標籤:des   blog   http   使用   strong   檔案   

10.1 GET請求

10.2 XML解析

10.3 JSON解析

10.4 POST請求

10.1 GET請求

通過一個第三方提供的雲端服務,查詢IP歸屬地:http://www.youdao.com/smartresult-xml/search.s?type=ip&q=218.241.121.186

它的返回格式是xml :

建立個例子:CSSimpleXML,設計原型:

編輯按鈕事件:

- (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];}

 

定義NSURLConnection的委託:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

NSURLConnection *connection = [[NSURLConnection alloc]   initWithRequest:request   delegate:self];

委託(delegate)是一種事件處理機制,當滿足條件時候觸發。delegate:self說明是委託當前對象處理事件,我們需要實現它們回調方法。

 NSURLConnection 回調方法

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 請求成功,並且接收資料。-(void) connection:(NSURLConnection *)connection  didFailWithError: (NSError *)error  請求成功,但是載入資料出現異常。-(void) connectionDidFinishLoading: (NSURLConnection*) connection載入資料成功,在connection:didReceiveData方法之後執行。

接收資料處理

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data {    //預設對於中文的支援不好    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);    NSString* gbkNSString = [[NSString alloc]initWithData:data encoding:enc];    //如果是黑UTF-8 NSXMLParese會報錯    xmlString = [[NSString alloc]initWithString:[gbkNSString stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"gbk\"?>" withString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"]];    NSLog(@"%@", xmlString);    [gbkNSString release];}

 

iPhone SDK提供的XML解析類只能解析utf-8編碼,如果從伺服器返回的xml編碼是gbk等,要轉換成utf-8再開始解析。

10.2 XML解析

關於iPhone發送GET請求,就是通過NSURLRequest和NSURLConnection兩個類實現的。

在眾多的回調方法。解析XML是在 connectionDidFinishLoading:方法開始的。

解析XML檔案也是要通過XML回調方式實現解析處理的。

NSXMLParser,是iPhone解析XML SDK工具類。

NSXMLParser採用SAX方式而不是DOM方式解析,SAX是基於事件觸發的解析方式,解析器從上到下遍曆xml文檔,遇到開始標籤、結束標籤、文檔開始、文檔結束和字串都會觸發事件。

 解析開始處理

 

-(void)connectionDidFinishLoading:(NSURLConnection*)connection {    [activityIndicator stopAnimating];    //開始解析XML    NSXMLParser* ipParser = [[NSXMLParser alloc]initWithData:[xmlString dataUsingEncoding:NSUTF8StringEncoding ]];;    ipParser.delegate = self;    [ipParser parse];    [ipParser release];}

 

NSXMLParser回調方法

- (void)parserDidStartDocument:(NSXMLParser *)parser文檔開始的時候觸發- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError  文檔出錯的時候觸發- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *) qualifiedName attributes:(NSDictionary *)attributeDict 遇到一個開始標籤時候觸發。- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 遇到字串時候觸發- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementNamenamespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName 遇到結束標籤時候出發。- (void)parserDidEndDocument:(NSXMLParser *)parser  遇到文檔結束時候觸發。

文檔開始的回調方法

這個方法在解析過程中只調運一次,一般在這個方法中進行有關解析的初始化處理。

//文檔開始的時候觸發- (void)parserDidStartDocument:(NSXMLParser *)parser {    info = [[NSMutableDictionary alloc]initWithCapacity:1];}

 

文檔出錯回調方法

//文檔出錯的時候觸發- (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];}

 

遇到開始標籤回調方法

參數elementName是標籤的名字,attributeDict 是屬性列表,namespaceURI 是命名空間,如果有命名空間qualifiedName是指定的首碼名。

//遇到一個開始標籤時候觸發。- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *) qualifiedName attributes:(NSDictionary *)attributeDict {    NSLog(@"value:%@\n", elementName);    currentTagName = elementName;}

 

遇到字串回調方法

//遇到字串時候觸發- (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];        }    }}

 

遇到結束標籤回調方法

//遇到結束標籤時候出發。- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementNamenamespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName {}

 

遇到結束文檔回調方法

// 遇到文檔結束時候觸發。- (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解析

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

獲得JSON:

{    status =     {        message = "the daily limit of 30000 credits demo has been exceeded.Please throttle your requests or use the commercial service.";        value = 18;    };}
10.3.1 JSON解析API

iPhone SDK沒有提供JSON解析API,可以使用第三方的API類庫json-framework,:

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

把Classes/JSON/下面的類拷貝到我們的工程的Classes目錄下面,右鍵添加存在的類檔案。

實現回調方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data - (void) connectionDidFinishLoading: (NSURLConnection*) connection-(void) connection:(NSURLConnection *)connection  didFailWithError: (NSError *)error 

connection:didReceiveData:

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data {    outString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];    NSLog(@"%@", outString);}

 

connectionDidFinishLoading:

outString的 JSONValue訊息獲得NSMutableDictionary,JSON api中提供了NSString的分類(Catelog)

-(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];}

 

文檔出錯回調方法

-(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];}

 

點擊按鈕事件

-(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請求

為了學習iPhone的POST請求,安排案例如下:

在畫面中輸入使用者名稱和密碼,然後以POST方式提交資料到伺服器端。

NSMutableURLRequest

POST請求與GET不同,不使用的NSURLRequest,而是使用NSMutableURLRequest類,這是一個可變的NSURLRequest類。

- (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];}

 

POST參數是以一個字串方式傳遞: memberIdOrCellphoneOrEmail=%@&&password=%@

[request setHTTPMethod:@"POST"];

知道要求方法為POST方法,但是要注意POST必須大寫。

[request setHTTPBody:postData];該語句是將要提交的資料放到請求體中。

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];}

 

文檔出錯回調方法

-(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];
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.