iOS 通過URL網路擷取XML資料的兩種方式

來源:互聯網
上載者:User

下面簡單介紹如何通過url擷取xml的兩種方式。

第一種方式相對簡單,使用NSData的建構函式dataWithContentsOfURL;不多解釋,直接上代碼咯。

    NSURL *url = [NSURL URLWithString:@"http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction"];         //A Boolean value that turns an indicator of network activity on or off.    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;        NSData *xmlData = [NSData dataWithContentsOfURL:url];        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;        NSString *xmlString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];        if (xmlData == nil) {        NSLog(@"File read failed!:%@", xmlString);    }    else {        NSLog(@"File read succeed!:%@",xmlString);    }

上面的  NSData *xmlData = [NSData dataWithContentsOfURL:url];
就是擷取xml的關鍵啦。

    注意:如果直接輸出xmlData的話會是一對unicode,所以用UTF-8編碼轉換成是String進行輸出就好啦。


第二種方式:通過NSURLConnection建立網路連接,並實現它的幾個委託方法,從而擷取資料。

代碼如下,應該可以看懂的。

@implementation ViewController {    BOOL getXmlDone;  //是否停止擷取xml資料的標誌    NSMutableData *xmlData;  //儲存獲得的xml資料}//自訂的一個方法- (void) getXML {//擷取xmlxmlData = [NSMutableData data];    //Clears the receiver’s cache, removing all stored cached URL responses.    //清除接收器的緩衝,刪除所有儲存的快取的URL的響應。    [[NSURLCache sharedURLCache] removeAllCachedResponses];NSURL *url = [NSURL URLWithString:@"http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction"];    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];    //create the connection with the request and start loading the data    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];    [self performSelectorOnMainThread:@selector(downloadStarted) withObject:nil waitUntilDone:NO];    if (urlConnection != nil) {        do {            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];        } while (!getXmlDone);    }}#pragma mark NSURLConnection Delegate methods- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {    return nil;}// Forward errors to the delegate.- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {    getXmlDone = YES;}// Called when a chunk of data has been downloaded.- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {    // Append the downloaded chunk of data.    [xmlData appendData:data];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection {    [self performSelectorOnMainThread:@selector(downloadEnded) withObject:nil waitUntilDone:NO];    getXmlDone = YES;}- (void)downloadStarted {[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;}- (void)downloadEnded {[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;}- (void)viewDidLoad{    [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.        [self getXML];    NSString *xmlString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];    NSLog(@"data: %@",xmlString);}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

小結一下,第一種簡單,一次性擷取所有的xml資料,第二種有點複雜,當然其靈活性也更好。

要驗證擷取的資料的準確性的話,就點擊你的url吧!http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction

OK,下一篇文章將會介紹如何解析xml。come on!

相關文章

聯繫我們

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