Harsh.C
Harsh.C

Reputation: 83

NSString is null when converted from a NSURL

I am using the Open Weather API to get live weather depending on the users location. I first make a variable called urllink and set it equal to the http request:

NSString *urllink = [NSString stringWithFormat:@"api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%@", lat, lng, WEATHERAPIKEY];

Then I convert that string to a url. Convert url back to string because I need to change it to NSData object:

NSURL *jsonURL = [NSURL URLWithString:[self urlEncodeValue:urllink]];
NSString *jsonDataString  = [[NSString alloc]initWithContentsOfURL:jsonURL]; // error on this line
NSLog(@"This is jsonDataString:%@", jsonDataString);
NSData *jsonData = [jsonDataString dataUsingEncoding:NSUTF8StringEncoding];

The urllink variable converts perfectly to NSURL. But when I try to convert the NSURL to NSString I get nil. Which in return gives me nil for NSData.

So why is the line:

 NSString *jsonDataString  = [[NSString alloc]initWithContentsOfURL:jsonURL];

giving me nil for jsonDataString?

Upvotes: 1

Views: 154

Answers (2)

StealthOne
StealthOne

Reputation: 195

you probably need an async, data may not yet be present

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // The code runs in background

    do Some Long Operation

});

Upvotes: 0

Rob
Rob

Reputation: 437552

You are missing the scheme (the https:// or http://) in your URL. Thus the request will fail. Furthermore, you should just use URLWithString directly:

NSString *urllink = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%@", lat, lng, WEATHERAPIKEY];

NSURL *jsonURL = [NSURL URLWithString:urllink];

The problem is that you're using initWithContentsOfURL, which is (a) synchronous; and (b) doesn't report errors.

You should use NSURLSession which is asynchronous and reports errors:

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:jsonURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (data == nil || error != nil) {
        NSLog(@"error: %@", error);
        return;
    }

    NSError *parseError;
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    if (responseObject) {
        NSLog(@"responseObject = %@", responseObject);
    } else {
        NSLog(@"parseError: %@", parseError);
        NSLog(@"responseString: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
}];
[task resume];

Upvotes: 4

Related Questions