2013-07-24 87 views
1

基本上我想构建一个简单的货币转换器,从网上动态获取数据(Atm best我想出的是:http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml,如果你知道任何更好的具有JSON结果,我会很感激它)。Objective C从URL获取字符串

现在我注意到它没有XML格式,就像我在一些教程中看到的一样,所以我想从URL中获取所有内容作为字符串并将其解析为字符串(我对字符串解析,在C++比赛中做了很多)。

我的问题是,我如何从URL获取字符串?

网址:http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml

+0

你可以发布你的网址的样本ta喜欢? –

+0

它确实看起来像XML。 – Caleb

回答

6

对于iOS 7+和OS X 10.9+使用:

NSURLSession *aSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
[[aSession dataTaskWithURL:[NSURL URLWithString:@"http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    if (((NSHTTPURLResponse *)response).statusCode == 200) { 
     if (data) { 
      NSString *contentOfURL = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      NSLog(@"%@", contentOfURL); 
     } 
    } 
}] resume]; 

对于早期版本的使用:

[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
    if (((NSHTTPURLResponse *)response).statusCode == 200) { 
     if (data) { 
      NSString *contentOfURL = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      NSLog(@"%@", contentOfURL); 
     } 
    } 
}]; 

如果你正在寻找一个更容易实现解决方案看看this link

+0

这是一个简单的解决方案,它可以在这种情况下工作,但它有两个问题:1)它是同步的,所以如果服务器响应速度慢,你的应用程序会出现挂起,直到它。 2)在一般情况下,你不能仅仅假设响应是UTF-8。你需要对字符编码更聪明。 – JeremyP

+0

@JeremyP是的,我完全同意你的第一点,你绝对不应该在运输代码中这样做。你的第二点,你的意思是即使XML中的编码表示可以改变“UTF-8”,或者你的意思是他们可以改变编码?那么你会更好地使用['stringWithContentsOfURL:usedEncoding:error:'](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html# // apple_ref/occ/clm/NSString/stringWithContentsOfURL:usedEncoding:error :) – HAS

+1

那么你可以在AsyncronousRequest的完成块中解析它,然后在完成时更新数据,不是吗? –