#import <CoreLocation/CoreLocation.h>
<CLLocationManagerDelegate>
/**
获取当前位置
*/
- (void)locationButton{
NSLog(@"=====获取当前位置");
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = 5.0;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization]; // 永久授权
[self.locationManager requestWhenInUseAuthorization]; //使用中授权
}
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// 获取当前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根据经纬度反向地理编译出地址信息
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
if (array.count > 0){
CLPlacemark *placemark = [array objectAtIndex:0];
NSLog(@"newLocation:%.2f=====%.2f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
//获取城市
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
NSLog(@"++++%@===%@",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
NSLog(@"city = %@", city);
NSLog(@"--%@",placemark.name);
NSLog(@"++++%@",placemark.subLocality);
NSLog(@"country == %@",placemark.country);//中国
NSLog(@"administrativeArea == %@%@%@%@",placemark.administrativeArea,placemark.administrativeArea,placemark.subLocality,placemark.name); //河北省
}
else if (error == nil && [array count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
[self.locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
//设置提醒
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"允许\"定位\"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//打开定位设置
NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingURL];
}];
UIAlertAction * canct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:canct];
[alert addAction:ok];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}