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