【发布时间】:2015-02-23 13:09:48
【问题描述】:
我尝试显示用户的当前位置(我主要需要邮政编码),当我启动应用程序时没有任何反应,应用程序只显示空标签而没有崩溃消息。 这是我的代码:
@implementation ViewController {
CLLocationManager *locationManager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}
@synthesize array, mytableView, latitudeLabel, longitudeLabel, addressLabel;
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
geocoder = [[CLGeocoder alloc] init];
}
- (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) {
longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
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];
addressLabel.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
【问题讨论】:
-
您是否将 plist 设置为允许位置授权?
-
我的 plist 中没有任何内容,所以我没有使用它。
-
您需要更新您的 plist:stackoverflow.com/a/24063578/2274694
-
它给了我经度和纬度,但没有给我地址。那是因为它是在模拟器上运行而不是在实际设备上运行的吗?
标签: ios objective-c cllocationmanager