iOS 11.3.1获取当前用户经纬度位置失败求助
解决iOS11.3.1上CoreLocation定位失效的问题
嘿,我来帮你搞定这个定位问题!iOS11之后CoreLocation的权限机制和旧版本有不少关键变化,这大概率是你代码跑不起来的核心原因,我整理了几个修复点和完整的适配代码:
1. 先搞定Info.plist的权限配置(必做)
iOS11及以后,Apple要求更明确的权限描述,旧版本的权限键在iOS11+上会直接失效,你需要在Info.plist中添加至少一个(按需选择):
NSLocationWhenInUseUsageDescription:APP前台使用定位时的说明(比如"需要获取您的位置来提供精准服务")NSLocationAlwaysAndWhenInUseUsageDescription:APP前后台都需使用定位时的说明
如果只加旧的NSLocationAlwaysUsageDescription,系统根本不会弹出权限请求框,定位自然无法工作。
2. 补全并修正你的CoreLocation代码
你的代码片段没写完,我帮你补全适配iOS11+的完整实现,还修正了一个拼写错误:
#import <CoreLocation/CoreLocation.h> @interface ViewController () <CLLocationManagerDelegate> @property (weak, nonatomic) IBOutlet UILabel *latitudeValue; @property (weak, nonatomic) IBOutlet UILabel *longitudeValue; // 修正原代码拼写错误:longtitude → longitude @property (nonatomic, strong) CLLocationManager *locationManager; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 初始化定位管理器,必须强引用(你已经用了strong,这步没问题) self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; // 设置定位精度,按需选择,精度越高耗电越大 self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 请求权限:根据业务需求选WhenInUse或Always if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) { // iOS11+推荐先请求前台权限,若需后台定位,再在用户允许后请求永久权限 [self.locationManager requestWhenInUseAuthorization]; // 如果需要后台定位,可在权限允许后调用: // [self.locationManager requestAlwaysAuthorization]; } } // 代理方法:权限状态变化时触发 - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) { // 权限允许,开始获取定位 [self.locationManager startUpdatingLocation]; } else { // 权限被拒绝,提示用户去设置开启 NSLog(@"定位权限被拒绝,请在系统设置中开启"); } } // 代理方法:成功获取到定位信息时触发 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { CLLocation *currentLocation = locations.lastObject; if (currentLocation) { // 更新UI显示经纬度 self.latitudeValue.text = [NSString stringWithFormat:@"纬度:%.6f", currentLocation.coordinate.latitude]; self.longitudeValue.text = [NSString stringWithFormat:@"经度:%.6f", currentLocation.coordinate.longitude]; // 如果只需要一次定位,这里可以停止更新以节省电量 [self.locationManager stopUpdatingLocation]; } } // 代理方法:定位失败时触发 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"定位失败:%@", error.localizedDescription); } @end
3. 额外注意事项
- 拼写错误:你原代码里的
longtitudeValue是拼写错误,这会导致UI控件无法关联,就算定位成功也显示不出结果! - 真机测试:模拟器需要手动设置模拟位置,真机要确保系统定位服务开启(设置→隐私→定位服务),且APP的权限被设为"允许"。
- 后台定位需求:如果需要APP在后台也能定位,除了添加
NSLocationAlwaysAndWhenInUseUsageDescription,还要在Xcode的Capabilities中开启Background Modes,勾选Location updates。
4. 排查步骤(如果还是不行)
- 检查Info.plist的权限键是否正确添加,描述内容不能为空。
- 查看Xcode控制台输出,是否有权限相关的错误日志。
- 确认设备的定位服务是否开启,以及APP的权限状态是否正常。
内容的提问来源于stack exchange,提问作者Genevios
相关产品推荐
相关产品推荐

