Cherry_thia
Cherry_thia

Reputation: 696

AFNetworking API call

I am trying to make an API call to get the weather forecast. But the call is not successful and perform the NSLog of error unsupported URL. However, I could get the JSON value with my browser. 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];

}

Upvotes: 0

Views: 334

Answers (1)

Paulw11
Paulw11

Reputation: 114773

Your URL is not well formed- you need to include the protocol (http://) - Web browsers will do this for you, but you need to specify it correctly in your app.

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

Upvotes: 2

Related Questions