AFNetworking API 调用

AFNetworking API call

我正在尝试拨打 API 电话以获取天气预报。但是调用不成功,执行 NSLog 错误 unsupported 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];

}

您的 URL 格式不正确 - 您需要包含协议 (http://) - Web 浏览器会为您完成此操作,但您需要在您的应用中正确指定它。

NSString *BaseURLString = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%.2f&lon=%.2f", Lat, Long];