项目配置
-
1: 需在项目配置中开启如下权限
- 2:在info.plist中添加
NSLocationAlwaysAndWhenInUseUsageDescription
及NSLocationWhenInUseUsageDescription
实现部分代码
demo点这里
//定位 相关参数设置
- (CLLocationManager *)locManager
{
if (!_locManager) {
_locManager = [[CLLocationManager alloc] init];
if ([_locManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
_locManager.allowsBackgroundLocationUpdates = YES;
}
_locManager.pausesLocationUpdatesAutomatically = NO;
_locManager.distanceFilter = kCLDistanceFilterNone;
_locManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
}
return _locManager;
}
- (void)startLocation
{
if ([CLLocationManager locationServicesEnabled] == NO) {
NSLog(@"locationServicesEnabled false");
} else {
CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
if(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted) {
NSLog(@"authorizationStatus failed");
} else {
NSLog(@"authorizationStatus authorized");
self.locManager.delegate = self;
[self.locManager requestAlwaysAuthorization];
// [self.locManager requestWhenInUseAuthorization];
[self.locManager startUpdatingLocation];
}
//回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
if (![self canUpload]) return;
CLLocation *loc = locations.firstObject;
NSLog(@"----- i = %d, 维度: %f, 经度: %f", i++, loc.coordinate.latitude, loc.coordinate.longitude);
//上传定位
[self uploadLocation:loc.coordinate];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"定位失败: %@", error);
}
- (BOOL)canUpload
{
CFTimeInterval t = CACurrentMediaTime();
if (t - self.lastUpdateTime > _interval) {
self.lastUpdateTime = t;
return YES;
}
return NO;
}
效果图
后言
由于截图是在位置不变的情况下进行的测试,位置不变,定位回调会间隔有点长,可能不会每60s(所设置的时间间隔)就回调一次, 但是如果在室外位置移动的情况及设置 _locManager.desiredAccuracy = kCLLocationAccuracyBest;
的情况下, 几乎可以达到每秒定位回调成功一次。