標籤:
CoreLocation匯入架構 :#import <CoreLocation/CoreLocation.h>
需要瞭解的基本的屬性和方法:
屬性:
- 定位管理者:CLLocationManager
- 請求定位許可權:requestAlwaysAuthorization
- 開始擷取位置:startUpdatingLocation
- 停止擷取位置:stopUpdatingLocation
- 授權認證狀態:CLAuthorizationStatus
- 過濾定位的距離:distanceFilter
- 定位所需精度:desiredAccuracy
- 定位到的資訊:CLLocation
- 建立經緯度點:CLLocationCoordinate2D
方法:
- 授權狀態發生改變:
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
- 擷取到位置資訊:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
- 進入監聽地區:
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
- 離開監聽地區:
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
CoreLocatio定位的基本操作:
在ios8後,系統不會預設幫我們調用定位授權,需要我們自己主動要求使用者給我們授權,我們需要調用此方法:
[self.mgr requestAlwaysAuthorization];
並且我們還需要在info.plist檔案中配置:
NSLocationWhenInUseDescription,允許在前台擷取GPS的描述
NSLocationAlwaysUsageDescription,允許在後台擷取GPS的描述
#import "ViewController.h"#import <CoreLocation/CoreLocation.h>@interface ViewController ()<CLLocationManagerDelegate>/** * 定位管理者 */@property (nonatomic ,strong) CLLocationManager *mgr;@end@implementation ViewController// 懶載入// 建立CoreLocation管理者- (CLLocationManager *)mgr{ if (!_mgr) { _mgr = [[CLLocationManager alloc] init]; } return _mgr;}- (void)viewDidLoad { [super viewDidLoad]; // 設定代理監聽擷取到的位置 self.mgr.delegate = self; // 判斷是否是iOS8 if([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { NSLog(@"是iOS8"); // 主動要求使用者對我們的程式授權, 授權狀態改變就會通知代理 [self.mgr requestAlwaysAuthorization]; }else { // 開始監聽(開始擷取位置) [self.mgr startUpdatingLocation]; } }// 授權狀態發生改變時調用- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{ if (status == kCLAuthorizationStatusNotDetermined) { NSLog(@"等待使用者授權"); }else if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) { NSLog(@"授權成功"); // 開始定位 [self.mgr startUpdatingLocation]; }else { NSLog(@"授權失敗"); }}#pragma mark - CLLocationManagerDelegate// 擷取到位置資訊之後就會調用(調用頻率非常高)- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ // 定位的資訊 // CLLocation *location = [locations lastObject]; }
ios CoreLocation定位服務