iOS 通过URL网络获取XML数据的两种方式

下面简单介绍如何通过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 {
	//获取xml
	xmlData = [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!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值