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

时间:2023-11-26 16:42:38

转载于:http://blog.****.net/crayondeng/article/details/8738768

下面简单介绍如何通过url获取xml的两种方式。

第一种方式相对简单,使用NSData的构造函数dataWithContentsOfURL;不多解释,直接上代码咯。

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

上面的  NSData *xmlData = [NSData dataWithContentsOfURL:url]; 就是获取xml的关键啦。

注意:如果直接输出xmlData的话会是一对unicode,所以用UTF-8编码转换成是String进行输出就好啦。

第二种方式:通过NSURLConnection建立网络连接,并实现它的几个委托方法,从而获取数据。

代码如下,应该可以看懂的。

  1. @implementation ViewController {
  2. BOOL getXmlDone;  //是否停止获取xml数据的标志
  3. NSMutableData *xmlData;  //存储获得的xml数据
  4. }
  5. //自定义的一个方法
  6. - (void) getXML {
  7. //获取xml
  8. xmlData = [NSMutableData data];
  9. //Clears the receiver’s cache, removing all stored cached URL responses.
  10. //清除接收器的缓存,删除所有存储的高速缓存的URL的响应。
  11. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  12. NSURL *url = [NSURL URLWithString:@"http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction"];
  13. NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
  14. //create the connection with the request and start loading the data
  15. NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  16. [self performSelectorOnMainThread:@selector(downloadStarted) withObject:nil waitUntilDone:NO];
  17. if (urlConnection != nil) {
  18. do {
  19. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  20. } while (!getXmlDone);
  21. }
  22. }
  23. #pragma mark NSURLConnection Delegate methods
  24. - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
  25. return nil;
  26. }
  27. // Forward errors to the delegate.
  28. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  29. getXmlDone = YES;
  30. }
  31. // Called when a chunk of data has been downloaded.
  32. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  33. // Append the downloaded chunk of data.
  34. [xmlData appendData:data];
  35. }
  36. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  37. [self performSelectorOnMainThread:@selector(downloadEnded) withObject:nil waitUntilDone:NO];
  38. getXmlDone = YES;
  39. }
  40. - (void)downloadStarted {
  41. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  42. }
  43. - (void)downloadEnded {
  44. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  45. }
  46. - (void)viewDidLoad
  47. {
  48. [super viewDidLoad];
  49. // Do any additional setup after loading the view, typically from a nib.
  50. [self getXML];
  51. NSString *xmlString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
  52. NSLog(@"data: %@",xmlString);
  53. }
  54. - (void)didReceiveMemoryWarning
  55. {
  56. [super didReceiveMemoryWarning];
  57. // Dispose of any resources that can be recreated.
  58. }
  59. @end

小结一下,第一种简单,一次性获取所有的xml数据,第二种有点复杂,当然其灵活性也更好。

要验证获取的数据的准确性的话,就点击你的url吧!http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction

OK,下一篇文章将会介绍如何解析xml。come on!