Reputation: 931
I'm using the Open Weather Map API to fetch the user's current weather.
When I run the request in Postman, I get a status code 200 and am able to receive data. However, in Xcode I get the error -1002
Here is the code executing the 'GET' request:
// Configure URL String
NSString *apiKey = @"MY_API_KEY";
NSString *urlString = [[NSString alloc] initWithFormat:@"api.openweathermap.org/data/2.5/weather?APPID=%@&lat=%@&lon=%@", apiKey, latitude, longitude];
NSString *encodedUrl = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedUrl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:theRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"Here is the json dict: %@", jsonDict);
NSLog(@"%@", response);
}
else {
NSLog(@"error: %@", error);
}
}] resume];
Again, the request here returns the error but in Postman I get no error when I run:
api.openweathermap.org/data/2.5/weather?APPID=MY_API_KEY&lat=33.712926&lon=-117.839181
What is the issue with how I'm setting up the request?
Upvotes: 0
Views: 583
Reputation: 3675
A URL needs a scheme part. Please make sure you include a protocol such as http
or https
in your URL string:
NSString *urlString = [[NSString alloc] initWithFormat:@"https://api.openweathermap.org/data/2.5/weather?APPID=%@&lat=%@&lon=%@", apiKey, latitude, longitude];
Upvotes: 6