1艰猬、首先在plist表里邊添加Privacy - Location Usage Description和NSLocationWhenInUseUsageDescription(這個是在程序使用期間進行定位,如果需要一直獲取纺铭,添加NSLocationAlwaysUsageDescription)悴了,都為String類型
2搏恤、其次在.m中引入CoreLocation/CoreLocation.h頭文件,并且遵循CLLocationManagerDelegate代理湃交。然后定義一個CLLocationManager對象挑社,代碼如下:
#import"CoreLocation/CoreLocation.h"
@interfaceViewController ()?
@property (strong, nonatomic) CLLocationManager*locationManager;
@end
if ([CLLocationManager locationServicesEnabled]) {//判斷定位操作是否被允許
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;//遵循代理
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 10.0f;
[_locationManager requestWhenInUseAuthorization];//使用程序其間允許訪問位置數(shù)據(jù)(iOS8以上版本定位需要)
[self.locationManager startUpdatingLocation];//開始定位
}else{//不能定位用戶的位置的情況再次進行判斷,并給與用戶提示
//1.提醒用戶檢查當(dāng)前的網(wǎng)絡(luò)狀況
//2.提醒用戶打開定位開關(guān)
}
}
#pragma mark === 定位代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
//當(dāng)前所在城市的坐標(biāo)值
CLLocation *currLocation = [locations lastObject];
NSLog(@"經(jīng)度=%f 緯度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
//根據(jù)經(jīng)緯度反向地理編譯出地址信息
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
NSDictionary *address = [placemark addressDictionary];
//? Country(國家)? State(省)? City(市)
NSLog(@"#####%@",address);
NSLog(@"%@", [address objectForKey:@"Country"]);
NSLog(@"%@", [address objectForKey:@"State"]);
NSLog(@"%@", [address objectForKey:@"City"]);
self.cllocationCity =[address objectForKey:@"City"];
}
}];
}
//定位失敗彈出提示框,點擊"打開定位"按鈕,會打開系統(tǒng)的設(shè)置,提示打開定位服務(wù)
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"允許\"定位\"提示" message:@"請在設(shè)置中打開定位" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * ok = [UIAlertAction actionWithTitle:@"打開定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//打開定位設(shè)置
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}];
UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alertVC addAction:cancel];
[alertVC addAction:ok];
[self presentViewController:alertVC animated:YES completion:nil];
}