iOS定位SDK提供后台持续定位的能力,可持久记录位置信息,适用于记轨迹录。
//对appDelegate的要求
#import <AMapFoundationKit/AMapFoundationKit.h>
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"9f56b924d3ec22433ef3a451effa33da";
return YES;
}
//引入AMapFoundationKit.h和AMapLocationKit.h这两个头文件:
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
//更改info.plist
将info.plist的字段改成NSLocationAlwaysUsageDescription字段。
//配置后台定位
依次执行:
a)左侧目录中选中工程名,开启 TARGETS->Capabilities->Background Modes
b)在 Background Modes中勾选 Location updates
/*核心代码
----------------------------------------------
*/
//初始化位置管理器
self.locationManager = [[AMapLocationManager alloc] init];
//设置委托
[self.locationManager setDelegate:self];
//保持程序持续定位状态,代码如下:
//设置允许后台定位参数,保持不会被系统挂起
[self.locationManager setPausesLocationUpdatesAutomatically:NO];
[self.locationManager setAllowsBackgroundLocationUpdates:YES];//iOS9(含)以上系统需设置
//开始持续定位
[self.locationManager startUpdatingLocation];
//在回调函数中,获取定位坐标,进行业务处理。
- (void)amapLocationManager:(MALocationManager *)manager didUpdateLocation:(CLLocation *)location
{
NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
//业务处理
}
SerialLocationViewController.h
#import <UIKit/UIKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
@interface SerialLocationViewController : UIViewController
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@end
SerialLocationViewController.m
#import "SerialLocationViewController.h"
@interface SerialLocationViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate>
@property (nonatomic, strong) UISegmentedControl *showSegment;
@property (nonatomic, strong) MAPointAnnotation *pointAnnotaiton;
@end
@implementation SerialLocationViewController
#pragma mark - Action Handle
- (void)configLocationManager
{
self.locationManager = [[AMapLocationManager alloc] init];
[self.locationManager setDelegate:self];
//设置不允许系统暂停定位
[self.locationManager setPausesLocationUpdatesAutomatically:NO];
//设置允许在后台定位
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
#pragma mark - Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
[self configLocationManager];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.navigationController.toolbar.translucent = YES;
self.navigationController.toolbarHidden = NO;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.locationManager startUpdatingLocation];
}
@end