IOS開發--雲開發(雲請求&&XML解析)

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

概要

       本章主要簡示了在IOS裡面如何發出雲請求,以及處理雲端返回的資料,包括NSUrl等以及XML解析部分的知識。具體使用是一個查詢IP的請求應用。

結果展示


(用了10幾次不讓用了)

流程概要

1.選取查詢IP的雲請求連結,並在瀏覽器裡面試試效果,瞭解查詢返回結果的格式

2.建立一個工程,拖拉一個UITextField和UIView,分別用作輸入IP地址資訊和查詢結果展示

3.在發出雲請求的時候,根據查詢的IP構造查詢的地址連結,然後使用NSURL產生連結,使用NSURLRequest構造請求,最後使用NSURLConnection發出請求

4.由於NSURLConnection是是一個非同步請求,所以處理其返回結果需要使用其代理,首先指定它的代理,然後實現其代理裡面的接收資料方法(connection:didReceiveData)和接收資料完成的方法(connectionDidFinishLoading)

5.在接收資料完成裡面使用NSXMLParser解析返回的結果(有需要使用其代理),由於該類是使用SAX的方式解析,所以使用感覺比較煩

6.擷取的查詢格式如下所示:

<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WebXml.com.cn/"><string>112.134.113.124</string><string>華中科技大學</string></ArrayOfString>

主要代碼h檔案

////  ViewController.h//  IPInfo////  Created by God Lin on 14/12/11.//  Copyright (c) 2014年 arbboter. All rights reserved.//#import <UIKit/UIKit.h>@interface ViewController : UIViewController{    IBOutlet UITextField* _textIP;    IBOutlet UITextView* _textResult;        NSString* _stringReciveData;    NSMutableDictionary* _dictIP;    NSMutableArray* _arrayIP;    NSString* _currentContext;}@property (nonatomic, retain) UITextField* _textIP;@property (nonatomic, retain) UITextView* _textResult;@property (nonatomic, retain) NSString* _stringReciveData;@property (nonatomic, retain) NSMutableDictionary* _dictIP;@property (nonatomic, retain) NSMutableArray* _arrayIP;@property (nonatomic, retain) NSString* _currentContext;-(IBAction)go;@end

m檔案

////  ViewController.m//  IPInfo////  Created by God Lin on 14/12/11.//  Copyright (c) 2014年 arbboter. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize _textIP;@synthesize _textResult;@synthesize _stringReciveData;@synthesize _arrayIP;@synthesize _dictIP;@synthesize _currentContext;-(IBAction)go{    _stringReciveData = @"";    [self._textIP resignFirstResponder];        // 請求串連    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://webservice.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx/getCountryCityByIp?theIpAddress=%@",self._textIP.text]];    NSURLRequest* request = [NSURLRequest requestWithURL:url];    [NSURLConnection connectionWithRequest:request delegate:self];}#pragma NSURLConnectionDelegate協議// 收到資料調用該方法,可能不是一次性收到所有資料,所以..- (void)connection:(NSURLConnection *)connection    didReceiveData:(NSData *)data{    NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];        if([self._stringReciveData length])    {        self._stringReciveData = [self._stringReciveData stringByAppendingString:str];    }    else    {        self._stringReciveData = str;    }    NSLog(@"%@",str);}// 資料接收完成調用該方法- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSXMLParser* xmlParser = [[NSXMLParser alloc] initWithData:[self._stringReciveData dataUsingEncoding:NSUTF8StringEncoding]];        xmlParser.delegate = self;    [xmlParser parse];}#pragma NSXMLParser協議// 開始解析XML調用該方法- (void)parserDidStartDocument:(NSXMLParser *)parser{    self._dictIP = [[NSMutableDictionary alloc] init];}// XML解析結束調用該方法- (void)parserDidEndDocument:(NSXMLParser *)parse{    NSString* info = nil;    static int n = 0;    for (id ip in self._dictIP)    {        info = [NSString stringWithFormat:                @"%-5d [%@, %@]\n", ++n, ip, [self._dictIP objectForKey:ip]];                self._textResult.text = [self._textResult.text stringByAppendingString:info];    }        [self._dictIP removeAllObjects];    self._textIP.text = @"";}// 解析XML遇到開始標籤調用該方法- (void)parser:(NSXMLParser *)parserdidStartElement:(NSString *)elementName  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName    attributes:(NSDictionary *)attributeDict{    if ([elementName isEqualToString:@"ArrayOfString"])    {        self._arrayIP = [[NSMutableArray alloc] init];    }    self._currentContext = @"";}// 解析XML遇到結束標籤調用該方法- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{    if([self._currentContext length] > 0)    {        [self._arrayIP addObject:self._currentContext];            }        if([self._arrayIP count] == 2)    {        [self._dictIP setObject:self._arrayIP[1] forKey:self._arrayIP[0]];    }}// 解析XML遇到標籤內容時調用該方法// (有可能一個標籤內容不止觸發該函數一次)- (void)parser:(NSXMLParser *)parserfoundCharacters:(NSString *)string{    // 去掉空格和換行    string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];    if([string length] > 0)    {        self._currentContext = [self._currentContext stringByAppendingString:string];    }}- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    self._textResult.editable = NO;    self._textResult.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];    self._textResult.textColor = [UIColor yellowColor];}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

工程代碼

IOS開發--雲開發(雲請求&&XML解析)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.