通過CoreLocation框架來獲得定位信息,還是比較簡單的,現總結如下:
1、引入CoreLocation框架
利用iOS7新特性,我們不需像之前那樣“target -> Build Phases ->Link Binary With Libraries”來導入框架,我們只需在需要用到定位的類中,這樣引入:
@import CoreLocation;
這被稱為“Modules”.
2、遵守CLLocationManagerDelegate協議
遵守CLLocationManagerDelegate協議
3、始于iOS8的分歧
iOS8之后,我們需要在APP的plist文件中增加兩個字段,才能調用定位,如圖:
plist文件中增加兩個字段
這兩個字段對應的Value可以為空,也可以自定義,自定義的文本內容會在請求授權的時候,展示在alertview中。
增加這兩個字段,可能是為了方便系統或者第三方SDK檢測你的APP是否使用了定位。
iOS8之前,并不強制添加這兩個字段。
接下來,我們開始實例化一個CLLocationManager
,這在iOS8前后略有區別。
iOS8之前:
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
//選擇定位的方式為最優的狀態,他有四種方式在文檔中能查到
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[self getLocation];
iOS8之后:
self.locationManager = [[CLLocationManager alloc]init];
//iOS8需要設置授權方式
//用到定位的時候授權
[self.locationManager requestWhenInUseAuthorization];
//或者選擇這種,不用定位時也授權
//[self.locationManager requestAlwaysAuthorization];
self.locationManager.delegate = self;
//選擇定位的方式為最優的狀態,他有四種方式在文檔中能查到
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;
}
當locationManager調用startUpdatingLocation
方法之后,CLLocationManagerDelegate的相關方法會執行。根據代理方法作相應的回調。
比如:
#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;
}
}
}
記得在這些定位授權結束后,關掉定位,調用stopUpdatingLocation
,這樣APP會更節能。
定位的基本使用就是這樣簡單。