首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AFNetworking API调用

AFNetworking API调用
EN

Stack Overflow用户
提问于 2015-07-23 04:18:59
回答 1查看 332关注 0票数 0

我正试着打一个API电话,以获得天气预报。但是调用不成功,并执行错误的NSLog不受支持的URL。但是,我可以使用浏览器获得JSON值。api.openweathermap.org/data/2.5/weather?lat=55.76&lon=37.62

代码语言:javascript
复制
- (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];

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-23 04:24:56

你的网址不是很好的格式-你需要包括协议(http://) -网络浏览器会为你这样做,但你需要正确地指定它在你的应用程序。

代码语言:javascript
复制
NSString *BaseURLString = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%.2f&lon=%.2f", Lat, Long];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31578081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档