我正试着打一个API电话,以获得天气预报。但是调用不成功,并执行错误的NSLog不受支持的URL。但是,我可以使用浏览器获得JSON值。api.openweathermap.org/data/2.5/weather?lat=55.76&lon=37.62
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (IBAction)getWeather:(id)sender {
float Lat = locationManager.location.coordinate.latitude;
float Long = locationManager.location.coordinate.longitude;
NSString *BaseURLString = [NSString stringWithFormat:@"api.openweathermap.org/data/2.5/weather?lat=%.2f&lon=%.2f", Lat, Long];
NSLog(@"%@",BaseURLString);
NSURL *url = [NSURL URLWithString:BaseURLString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//Success here
NSString *weather = [JSON valueForKey:@"weather.main"];
NSLog(@"%@",weather);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
//Error Here
NSLog(@"\nError contacting WeatherAPI: %@", [error localizedDescription]);
}];
[operation start];
}发布于 2015-07-23 04:24:56
你的网址不是很好的格式-你需要包括协议(http://) -网络浏览器会为你这样做,但你需要正确地指定它在你的应用程序。
NSString *BaseURLString = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%.2f&lon=%.2f", Lat, Long];https://stackoverflow.com/questions/31578081
复制相似问题