【发布时间】:2015-02-23 21:34:58
【问题描述】:
我正在尝试让我的应用以类似地址的形式(位于“反向地理编码”注释之后)找到用户的位置。以下是我的代码:
- (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,我将不胜感激。提前感谢所有回复的人。
***顺便说一句:以下几行在我的 viewDidLoad 部分: locationManager = [[CLLocationManager alloc] init]; geocoder = [[CLGeocoder alloc] init];
【问题讨论】:
-
仅供参考-记录任何内容的不是编译器。记录消息的是您正在运行的应用程序。
-
好的。这就是我要打字的意思。对此可能造成的任何混乱,我们深表歉意。
-
除了在设置值之前访问地址变量之外,您还需要确保在 info.plist 中放入了适当的原因字符串并调用了
requestWhenInUseAuthorization。您还使用了已弃用的位置委托方法。你应该使用didUpdateLocations:。最后,在收到第一个位置后禁用位置更新并不是一个好主意,因为第一个位置可能不会很准确。您应该继续接收更新,可能会等待CLLocation的horizonalAccuracy属性中的低值 -
@Paulw11 感谢您的快速回复!我对 Objective-C 编程相当陌生,所以我应该把它放在我的 info.plist 文件中的什么位置?我在这个文件的任何地方都没有看到原因字符串选项。另外,我如何获得我的应用请求权限以接收对用户当前位置的访问权限?
标签: ios objective-c null geolocation core-location