Objective C /从URL获取字符串

Lor*_*olt 1 string url objective-c nsstring

基本上我想建立一个简单的货币转换器,从网络上动态获取数据(Atm最好我提出的是:http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml,如果你知道有更好的JSON结果,我很感激).

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

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

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

HAS*_*HAS 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];
Run Code Online (Sandbox Code Playgroud)

对于早期版本使用:

[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);
        }
    }
}];
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找更容易实施的解决方案,请查看此链接