我想让我的应用程序以类似地址的形式(位于“反向地理编码”评论之后)找到用户的位置。下面是我的代码:Objective-C:查找用户位置(不在地图上)
- (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);
}
} ];
}
我的问题是,编译器只打印出“(空)”。 (我这样做的线位于“getuserlocation”IBAction。)我不确定这是为什么。我已经在实际的iPhone 6 Plus上测试了应用程序,这与模拟器不同,它可以访问定位服务。
如果有人能够指出我的代码中的错误/问题在哪里,导致它打印出null,我将不胜感激。预先感谢所有回复的人。
***顺便说一句:以下行在我的viewDidLoad部分: locationManager = [[CLLocationManager alloc] init]; geocoder = [[CLGeocoder alloc] init];
仅供参考 - 编译器并不记录任何内容。这是您正在运行的应用程序正在记录消息。 – rmaddy 2015-02-23 21:47:11
好的。这就是我打算输入的内容。对不起,这可能造成的任何混淆。 – iProgramIt 2015-02-23 21:48:47
除了在设置值之前访问地址变量之外,还需要确保将适当的原因字符串放入info.plist中,并调用requestWhenInUseAuthorization。您还正在使用不推荐使用的位置委托方法。你应该使用'didUpdateLocations:'。最后,在收到第一个位置后禁用位置更新并不是一个好主意,因为第一个位置可能不会很准确。你应该继续收到更新,或许正在'CLLocation'的'horizonalAccuracy'属性中等待一个较低的值。 – Paulw11 2015-02-23 21:58:00