Lord Zsolt
Lord Zsolt

Reputation: 6557

Objective C / Get string from URL

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

Upvotes: 2

Views: 5906

Answers (1)

HAS
HAS

Reputation: 19873

For iOS 7+ and OS X 10.9+ use:

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];

For earlier versions use:

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

If you are looking for an easier to implement solution take a look at this link

Upvotes: 7

Related Questions