2

Basically I'd like to build a simple currency converter that fetches data dynamically from the web (Atm best I've come up with is: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml , if you know any better that has a JSON result, I'd appreciate it).

Now I noticed it doesn't have the XML format like I've seen in some tutorials, so I thought about getting everything from the URL as string and parsing it as a string (I'm pretty good with string parsing, done a lot at C++ contests).

My question is, how do I get the string from the URL?

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

4

1 回答 1

7

对于 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);
        }
    }
}];

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

于 2013-07-24T16:01:14.287 回答