我正在尝试让我的应用以类似地址的形式(位于“反向地理编码”评论之后)找到用户的位置。以下是我的代码:
- (IBAction)getuserlocation:(id) sender{
//Getting Location
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSLog(address);
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
latitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
address = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
我的问题是编译器只打印出“(null)”。 (我这样做的行位于“getuserlocation”IBAction。)我不知道为什么会这样。我在实际的iPhone 6 Plus上测试了应用程序,它与模拟器不同,可以访问位置服务。
如果有人能够指出我的代码中的错误/问题在哪里,导致它打印出null,我将非常感激。提前感谢所有回复的人。
*** BTW:我的viewDidLoad部分包含以下几行: locationManager = [[CLLocationManager alloc] init]; geocoder = [[CLGeocoder alloc] init];
答案 0 :(得分:0)
您在获取位置并将其转换为地址之前很久就会记录address
。
将NSLog(address);
移至您实际为address
指定值的位置之后。
顺便说一句 - 它应该更像是:NSLog(@"Address: %@, address);
。