通過CoreLocation框架來獲得定位信息,還是比較簡(jiǎn)單的,現(xiàn)總結(jié)如下:
1、引入CoreLocation框架
利用iOS7新特性,我們不需像之前那樣“target -> Build Phases ->Link Binary With Libraries”來導(dǎo)入框架,我們只需在需要用到定位的類中,這樣引入:
@import CoreLocation;
這被稱為“Modules”.
2、遵守CLLocationManagerDelegate協(xié)議
遵守CLLocationManagerDelegate協(xié)議
3、始于iOS8的分歧
iOS8之后,我們需要在APP的plist文件中增加兩個(gè)字段,才能調(diào)用定位,如圖:
plist文件中增加兩個(gè)字段
這兩個(gè)字段對(duì)應(yīng)的Value可以為空,也可以自定義,自定義的文本內(nèi)容會(huì)在請(qǐng)求授權(quán)的時(shí)候,展示在alertview中。
增加這兩個(gè)字段,可能是為了方便系統(tǒng)或者第三方SDK檢測(cè)你的APP是否使用了定位。
iOS8之前,并不強(qiáng)制添加這兩個(gè)字段。
接下來,我們開始實(shí)例化一個(gè)CLLocationManager
,這在iOS8前后略有區(qū)別。
iOS8之前:
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
//選擇定位的方式為最優(yōu)的狀態(tài),他有四種方式在文檔中能查到
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[self getLocation];
iOS8之后:
self.locationManager = [[CLLocationManager alloc]init];
//iOS8需要設(shè)置授權(quán)方式
//用到定位的時(shí)候授權(quán)
[self.locationManager requestWhenInUseAuthorization];
//或者選擇這種,不用定位時(shí)也授權(quán)
//[self.locationManager requestAlwaysAuthorization];
self.locationManager.delegate = self;
//選擇定位的方式為最優(yōu)的狀態(tài),他有四種方式在文檔中能查到
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[self getLocation];
4、開始定位:
-(NSString*)getLocation
{
[self.locationManager startUpdatingLocation];
NSString* latitude = [NSString stringWithFormat:@"%f,",_locationManager.location.coordinate.latitude];
NSString* longitude = [NSString stringWithFormat:@"%f",_locationManager.location.coordinate.longitude];
NSString* location = [NSString stringWithFormat:@"%@%@",latitude,longitude];
return location;
}
當(dāng)locationManager調(diào)用startUpdatingLocation
方法之后,CLLocationManagerDelegate的相關(guān)方法會(huì)執(zhí)行。根據(jù)代理方法作相應(yīng)的回調(diào)。
比如:
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status == kCLAuthorizationStatusDenied) {
self.location = @"";
[self performSelectorInBackground:@selector(archiveClientData) withObject:nil];
[manager stopUpdatingLocation];
self.locationManager.delegate = nil;
}else if (status == kCLAuthorizationStatusAuthorized){
self.location = [self getLocation];
[self performSelectorInBackground:@selector(archiveClientData) withObject:nil];
[manager stopUpdatingLocation];
self.locationManager.delegate = nil;
}
if([[[UIDevice currentDevice]systemVersion]floatValue]>=8.0){
if (status == kCLAuthorizationStatusAuthorizedWhenInUse){
self.location = [self getLocation];
[self performSelectorInBackground:@selector(archiveClientData) withObject:nil];
[manager stopUpdatingLocation];
self.locationManager.delegate = nil;
}
}
}
記得在這些定位授權(quán)結(jié)束后,關(guān)掉定位,調(diào)用stopUpdatingLocation
,這樣APP會(huì)更節(jié)能。
定位的基本使用就是這樣簡(jiǎn)單。