我正在使用Open Weather Map API来获取用户当前的天气。
当我在Postman中运行请求时,我得到状态代码200并且能够接收数据。但是,在Xcode中我收到错误-1002
以下是执行'GET'请求的代码:
// 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];
同样,这里的请求会返回错误但在Postman中我运行时没有错误:
api.openweathermap.org/data/2.5/weather?APPID=MY_API_KEY&lat=33.712926&lon=-117.839181
我如何设置请求有什么问题?
答案 0 :(得分:5)
URL需要方案部分。请确保在您的网址字符串中添加http
或https
等协议:
NSString *urlString = [[NSString alloc] initWithFormat:@"https://api.openweathermap.org/data/2.5/weather?APPID=%@&lat=%@&lon=%@", apiKey, latitude, longitude];