Search code examples
iosbrowseropenweathermap

I have an openweathermap API issue with iOS app


I am using openweathermap API in my iOS app.

Below is my URL which I am calling to get weather info.

http://api.openweathermap.org/data/2.5/weather?lat=21.282778&lon=-157.829444&APPID=MYAPPID&lang=en-US

When I open this URL in a browser I get a proper response.

But when I call the web service from my iOS app, I do not get a response.

I get the following error:

{
    cod = 401;
    message = "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info.";
}

I had created an API key from this URL: Create API key on Open Wheather


Solution

  • NSURL *URL = [NSURL URLWithString:@"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a&lang=en-US"];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
        {
            NSError* errorObj;
            NSDictionary* json = [NSJSONSerialization
                                  JSONObjectWithData:data
                                  options:kNilOptions
                                  error:&errorObj];
    
            NSLog(@" response is %@",json);
    
        }];
    
        [task resume];
    

    You app id should be valid. I have hardcoded the url for demonstration.