iOS 后台持续定位详解(支持ISO9.0以上)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 后台持续定位详解(支持ISO9.0以上)相关的知识,希望对你有一定的参考价值。
ios 后台持续定位详解(支持ISO9.0以上)
#import <CoreLocation/CoreLocation.h>并实现CLLocationManagerDelegate 代理,.h文件完整代码如下:
- #import <UIKit/UIKit.h>
- #import <CoreLocation/CoreLocation.h>
- @interface ViewController : UIViewController<CLLocationManagerDelegate>
- @end
2.info.list文件:
右键,Add Row,添加的Key为NSLocationAlwaysUsageDescription,其它值默认,示例如下:
3.添加后台定位权限
4.ViewController.m 文件:
(1)定义一个私有CLLocationManager对象
(2)初始化并设置参数(initLocation方法),其中
locationManager.desiredAccuracy设置定位精度,有六个值可选,精度依次递减
kCLLocationAccuracyBestForNavigation
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyKilometer
kCLLocationAccuracyThreeKilometers
locationManager.pausesLocationUpdatesAutomatically 设置是否允许系统自动暂停定位,这里要设置为NO,刚开始我没有设置,后台定位持续20分钟左右就停止了!
(3)实现CLLocationManagerDelegate的代理方法,此方法在每次定位成功后调用:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations;
*也可以通过实现以下方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
(4)实现CLLocationManagerDelegate的代理方法,此方法在定位出错后调用:
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
- #import "ViewController.h"
- @interface ViewController (){
- CLLocationManager *locationManager;
- CLLocation *newLocation;
- CLLocationCoordinate2D coordinate;
- }
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- [self initLocation];
- }
- #pragma mark 初始化定位
- -(void)initLocation {
- locationManager=[[CLLocationManager alloc] init];
- locationManager.delegate = self;
- locationManager.desiredAccuracy = kCLLocationAccuracyBest;//设置定位精度
- if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
- [locationManager requestAlwaysAuthorization];
- }
-
// 9.0以后这个必须要加不加是不能实现后台持续定位的的
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
locationManager.allowsBackgroundLocationUpdates = YES;
}
- if(![CLLocationManager locationServicesEnabled]){
- NSLog(@"请开启定位:设置 > 隐私 > 位置 > 定位服务");
- }
- locationManager.pausesLocationUpdatesAutomatically = NO;
- [locationManager startUpdatingLocation];
- //[locationManager startMonitoringSignificantLocationChanges];
- }
- #pragma mark 定位成功
- -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
- newLocation = [locations lastObject];
- double lat = newLocation.coordinate.latitude;
- double lon = newLocation.coordinate.longitude;
- NSLog(@"lat:%f,lon:%f",lat,lon);
- }
- #pragma mark 定位失败
- -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
- NSLog(@"error:%@",error);
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
以上是关于iOS 后台持续定位详解(支持ISO9.0以上)的主要内容,如果未能解决你的问题,请参考以下文章