【问题标题】:AFNetworking API callAFNetworking API 调用
【发布时间】:2015-07-23 04:18:59
【问题描述】:

我正在尝试调用 API 来获取天气预报。但是调用不成功并执行错误不支持 URL 的 NSLog。但是,我可以使用我的浏览器获取 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];

}

【问题讨论】:

  • @InderKumarRathore 刚刚添加
  • api调用是否因failure:块而失败,在这种情况下,日志中的错误是什么

标签: ios objective-c afnetworking


【解决方案1】:

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

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

【讨论】:

  • 酷它工作! @巴文。但是,我的天气的返回值为 NULL。为什么?
  • weather.main 不是有效键 - 您需要检索与 weather 关联的字典,然后从中访问 main
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
相关资源
最近更新 更多