无法使用lat / long - throws类型错误反转geolocate

时间:2014-09-13 20:36:00

标签: objective-c geolocation cllocation

我能够获得用户的纬度和经度并在控制台日志中正确显示...但我无法将地理位置反转为城市名称或其他任何内容。

我做错了什么?

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *userlatitude = [locations lastObject];
    CLLocation *userlongitude = [locations objectAtIndex:locations.count-2];        
    CLGeocoder *ceo = [[CLGeocoder alloc]init];
    CLLocation *loc = [[CLLocation alloc]initWithLatitude:userlatitude longitude:userlongitude];

    [ceo reverseGeocodeLocation: loc completionHandler: ^(NSArray *placemarks, NSError *error) {
         CLPlacemark *placemark = [placemarks objectAtIndex:0];
         NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
         NSLog(@"Currently located at %@",locatedAt);
     }];

    [locationManager stopUpdatingLocation];
}

我也尝试用

替换CLLocation *userlatitude .... objectAtIndex:location.count-2];
CLLocationDegrees userlatitude = [[locations lastObject] doubleValue];
CLLocationDegrees userlongitude = [[locations objectAtIndex:locations.count-2] doubleValue]; 

但是这会在运行时返回错误(即使它在代码编辑器中没有显示任何语法错误)。

1 个答案:

答案 0 :(得分:1)

didUpdateLocations方法返回包含位置数据的CLLocation个对象数组。此数组始终包含至少一个表示当前位置的对象。

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLGeocoder *ceo = [[CLGeocoder alloc]init];

    [ceo reverseGeocodeLocation:(CLLocation *)[locations lastObject] // pass the most recent value
              completionHandler: ^(NSArray *placemarks, NSError *error) {

                  if (error) {
                      NSLog(@"reverse error: %@", error);
                      // handle error here
                      return;
                  }

                  CLPlacemark *placemark = [placemarks objectAtIndex:0];
                  NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"]
                                         componentsJoinedByString:@", "];

                  NSLog(@"Currently located at %@",locatedAt);

    }];

}