CoreLocation:用于地理定位,地理編碼, 區(qū)域監(jiān)聽等(著重功能實(shí)現(xiàn))
MapKit:用于地圖展示,例如大頭針,路線,覆蓋層展示等(著重界面展示)
定位是一個(gè)很常用的功能,如一些地圖軟件打開之后如果用戶允許軟件定位的話,那么打開軟件后就會(huì)自動(dòng)鎖定到當(dāng)前位置,如果用戶手機(jī)移動(dòng)那么當(dāng)前位置也會(huì)跟隨著變化。要實(shí)現(xiàn)這個(gè)功能需要使用Core Loaction中CLLocationManager類。首先看一下這個(gè)類的一些主要方法和屬性:




iOS 8 還提供了更加人性化的定位服務(wù)選項(xiàng)。App 的定位服務(wù)不再僅僅是關(guān)閉或打開,現(xiàn)在,定位服務(wù)的啟用提供了三個(gè)選項(xiàng),「永不」「使用應(yīng)用程序期間」和「始終」。同時(shí),考慮到能耗問題,如果一款 App 要求始終能在后臺(tái)開啟定位服務(wù),iOS 8 不僅會(huì)在首次打開 App 時(shí)主動(dòng)向你詢問,還會(huì)在日常使用中彈窗提醒你該 App 一直在后臺(tái)使用定位服務(wù),并詢問你是否繼續(xù)允許。在iOS7及以前的版本,如果在應(yīng)用程序中使用定位服務(wù)只要在程序中調(diào)用startUpdatingLocation方法應(yīng)用就會(huì)詢問用戶是否允許此應(yīng)用是否允許使用定位服務(wù),同時(shí)在提示過程中可以通過在info.plist中配置通過配置Privacy - Location Usage Description告訴用戶使用的目的,同時(shí)這個(gè)配置是可選的。
但是在iOS8中配置配置項(xiàng)發(fā)生了變化,可以通過配置NSLocationAlwaysUsageDescription或者NSLocationWhenInUseUsageDescription來告訴用戶使用定位服務(wù)的目的,并且注意這個(gè)配置是必須的,如果不進(jìn)行配置則默認(rèn)情況下應(yīng)用無法使用定位服務(wù),打開應(yīng)用不會(huì)給出打開定位服務(wù)的提示,除非安裝后自己設(shè)置此應(yīng)用的定位服務(wù)。同時(shí),在應(yīng)用程序中需要根據(jù)配置對(duì)requestAlwaysAuthorization或locationServicesEnabled方法進(jìn)行請(qǐng)求。由于本人機(jī)器已經(jīng)更新到最新的iOS8.1下面的內(nèi)容主要針對(duì)iOS8,使用iOS7的朋友需要稍作調(diào)整。
////? KCMainViewController.m
//#import "KCMainViewController.h"
@interface KCMainViewController (){
CLLocationManager *_locationManager;
}
@end
@implementation KCMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
//定位管理器
_locationManager=[[CLLocationManager alloc]init];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服務(wù)當(dāng)前可能尚未打開,請(qǐng)?jiān)O(shè)置打開!");
return;
}
//如果沒有授權(quán)則請(qǐng)求用戶授權(quán)
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
[_locationManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
//設(shè)置代理
_locationManager.delegate=self;
//設(shè)置定位精度
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//定位頻率,每隔多少米定位一次
CLLocationDistance distance=10.0;//十米定位一次
_locationManager.distanceFilter=distance;
//啟動(dòng)跟蹤定位
[_locationManager startUpdatingLocation];
}
}
#pragma mark - CoreLocation 代理
#pragma mark 跟蹤定位代理方法,每次位置發(fā)生變化即會(huì)執(zhí)行(只要定位到相應(yīng)位置)
//可以通過模擬器設(shè)置一個(gè)虛擬位置,否則在模擬器中無法調(diào)用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *location=[locations firstObject];//取出第一個(gè)位置
CLLocationCoordinate2D coordinate=location.coordinate;//位置坐標(biāo)
NSLog(@"經(jīng)度:%f,緯度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
//如果不需要實(shí)時(shí)定位,使用完即使關(guān)閉定位服務(wù)
[_locationManager stopUpdatingLocation];
}
@end