1、要導入定位工具包。
#import <CoreLocation/CoreLocation.h>
2、全局CLLocationManager對象,用于定位。一定要全局,不然會因為引用計數變成0導致定位開啟就沒了后文。一定要全局!一定要全局!重要的事情說三遍。
@property (nonatomic, strong) CLLocationManager *locationManager;
3、創建CLLocationManager對象,開啟定位方法。
//開始定位
- (void)startLocation {
if ([CLLocationManager locationServicesEnabled]) {
//? ? ? ? CLog(@"--------開始定位");
self.locationManager = [[CLLocationManager alloc]init];
//設置代理
self.locationManager.delegate = self;
//控制定位精度,越高耗電量越
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// 詢問用戶總是授權可以定位
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
self.locationManager.distanceFilter = 10.0f;
//開始定位
[self.locationManager startUpdatingLocation];
}
}
4、簽訂代理<CLLocationManagerDelegate>,并實現兩個代理方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {? ? if ([error code] == kCLErrorDenied) {? ? ? ? //? ? ? ? CLog(@"訪問被拒絕");? ? }? ? if ([error code] == kCLErrorLocationUnknown) {? ? ? ? //? ? ? ? CLog(@"無法獲取位置信息");? ? }}
//定位代理經緯度回調
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations {
CLLocation *newLocation = locations[0];
//拿到定位信息,判斷是非是中國,判斷碼是“CN”
[[[CLGeocoder alloc]init] reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (error || placemarks.count == 0) {
NSLog(@"不能確定是在中國");
} else {
CLPlacemark *placemark=[placemarks firstObject];
if ([placemark.ISOcountryCode isEqualToString:@"CN"]) {
NSLog(@"確定是在中國");
} else {
NSLog(@"確定不在中國");
}
}
}];
//系統會一直更新數據,直到選擇停止更新,因為我們只需要獲得一次經緯度即可,所以獲取之后就停止更新
[manager stopUpdatingLocation];
}
5、在infoplist文件中加入Privacy - Location When In Use Usage Description,值為顯示的提示信息,可以自定義。
大功告成!