1

I am extremely confused with the NSUrlSession and the API. This is my first time trying to use an API so please explain this in the simplest form possible.

I found an API which gets the weather, I have made a string for the weather location. then did all the NSUrl / nsurlrequest. My goal is to output everything so I can see the keys of that API. Heres what I have so far but all It displays is 'Program ended with exit code 0'

I don't really know what is happening during the NSUrlsession because I learned how to use API with the NSUrlConnection via a youtube video.

 NSString *location = @"London";

    NSString *weatherString = [NSString stringWithFormat:@"https://api.openweathermap.org/data/2.5/weather?q=%@", location];
    NSURL *weatherURL = [NSURL URLWithString:weatherString];

    NSURLRequest *request = [NSURLRequest requestWithURL:weatherURL];

    NSURLSession *session = [NSURLSession sharedSession];



    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error){

                                  NSDictionary *weatherDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                                                        options:NSJSONReadingMutableContainers
                                                                                                              error:nil];
 NSLog(@"%@", [weatherDictionary description]);                                          
}];

1 Answers1

0

It's hard to tell from this snippet, but one or more of the following problems are likely causing your issues:

  1. You are retaining a reference to that task somewhere, right?
  2. From the documentation for dataTaskWithRequest, you need to call [task resume] to actually start the task.
  3. That URL won't work, because the api.openweathermap.org site doesn't support HTTPS. You'll need to change it to http, and possibly add an exception in the app's Info.plist to allow non-secure connections (they're disabled by default for new apps).
  4. After you fix all that, you'll need an API key for the request to actually succeed.
Mark Bessey
  • 19,598
  • 4
  • 47
  • 69