iOS自带定位的使用

配置:

  1. info.plist中配置Privacy - Location When In Use Usage Description
  2. 导入库文件#import <CoreLocation/CoreLocation.h>

代码:

#import "RootViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface RootViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

#implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startLocation];
}

// 开启定位
- (void)startLocation {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//最精准
    
    /** 由于IOS8中定位的授权机制改变 需要进行手动授权
     * 获取授权认证,两个方法:
     * [self.locationManager requestWhenInUseAuthorization];
     * [self.locationManager requestAlwaysAuthorization];
     */
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        NSLog(@"requestWhenInUseAuthorization");
        //  [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }
    // 开始定位,不断调用其代理方法
    [self.locationManager startUpdatingLocation];
}

#pragma mark  【 CLLocationManagerDelegate 】
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    // 1.获取用户位置的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
    longitute = coordinate.longitude;
    latitude = coordinate.latitude;
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
     {
         for (CLPlacemark * placemark in placemarks) {
             
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                 city = placemark.administrativeArea;
             }
             NSDictionary *dictionary = [placemark addressDictionary];
             NSLog(@"国家:%@",[dictionary objectForKey:@"Country"]);
             NSLog(@"省:%@",[dictionary objectForKey:@"State"]);
             NSLog(@"市:%@",city);
             NSLog(@"区:%@",placemark.subLocality);
             NSLog(@"街道:%@",placemark.thoroughfare);
             NSLog(@"子街道:%@",placemark.subThoroughfare);
         }
         if (error == nil && [placemarks count] == 0) {
             NSLog(@"No results were returned.");
         } else if (error != nil) {
             NSLog(@"An error occurred = %@", error);
         }
     }];
    
    // 2.停止定位
    [manager stopUpdatingLocation];
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容