iOS开发:如何将allowsBackgroundLocationUpdates设置为YES?
iOS后台位置更新:设置allowsBackgroundLocationUpdates的正确位置
没问题,这个确实是iOS位置服务里容易踩的新手坑,我来给你说清楚怎么弄:
核心位置:CLLocationManager实例配置阶段设置
你需要在创建并配置CLLocationManager实例之后,请求位置权限/开始位置更新之前,把allowsBackgroundLocationUpdates设为YES。这个顺序很重要,提前设置才能让后台更新的配置生效。
举个具体的代码示例:
Swift 代码示例
import CoreLocation class LocationHandler: NSObject, CLLocationManagerDelegate { private let locationManager = CLLocationManager() override init() { super.init() locationManager.delegate = self // 先开启后台位置更新允许 locationManager.allowsBackgroundLocationUpdates = true // 根据你的业务需求请求对应权限(Always权限更适合后台持续更新场景) locationManager.requestAlwaysAuthorization() // 启动位置更新 locationManager.startUpdatingLocation() } // 实现必要的代理方法处理位置回调... func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // 在这里处理位置更新,向服务器发送数据 } }
Objective-C 代码示例
#import <CoreLocation/CoreLocation.h> @interface LocationHandler () <CLLocationManagerDelegate> @property (nonatomic, strong) CLLocationManager *locationManager; @end @implementation LocationHandler - (instancetype)init { self = [super init]; if (self) { _locationManager = [[CLLocationManager alloc] init]; _locationManager.delegate = self; // 设置后台位置更新允许 _locationManager.allowsBackgroundLocationUpdates = YES; // 请求Always权限以支持后台持续更新 [_locationManager requestAlwaysAuthorization]; // 启动位置更新 [_locationManager startUpdatingLocation]; } return self; } // 实现代理方法处理位置回调 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { // 在这里处理位置数据并发送到服务器 } @end
几个关键注意事项
- 别忘了在Info.plist中添加权限描述:比如
NSLocationAlwaysAndWhenInUseUsageDescription(对应Always权限)或NSLocationWhenInUseUsageDescription,苹果要求必须有明确的权限说明,否则权限请求弹窗不会出现,甚至导致崩溃。 - 你已经配置的
Required background modes - App registers for location updates是必要前提,必须和allowsBackgroundLocationUpdates配合使用,二者缺一都无法实现后台位置更新。 - 谨慎使用该功能:后台位置更新会大幅增加设备耗电量,苹果审核时也会严格核查应用的使用场景是否真的需要该功能(比如导航、运动追踪类App才合理),避免不必要的配置。
内容的提问来源于stack exchange,提问作者B-Brennan




