获取当前城市

来源:互联网 发布:ubuntu文档 编辑:程序博客网 时间:2024/05/29 14:31

首先在info.plist文件中添加NSLocationAlwaysUsageDescription 类型为Boolean 值为YES

#import "ViewController.h"

#import <CoreLocation/CoreLocation.h>



@interface ViewController ()<CLLocationManagerDelegate>

@property (nonatomic,strong)CLLocationManager *manager;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    if (![CLLocationManagerlocationServicesEnabled]) {

        NSLog(@"定位服务没有打开");

        return;

    }

    //2.判断程序是否允许使用定位

    CLLocationManager *mgr=[[CLLocationManageralloc] init];

    self.manager=mgr;

    if ([CLLocationManagerauthorizationStatus]!=kCLAuthorizationStatusAuthorizedAlways) {

        [mgr requestAlwaysAuthorization];//ios系统发送允许使用定位请求。

    }

    //设置定位的精度,精度越高,越费电

    mgr.desiredAccuracy=kCLLocationAccuracyBest;

    //定位距离-m

    mgr.distanceFilter=100;

    mgr.delegate=self;

    [mgr startUpdatingLocation];

    

}

#pragma mark --CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *cloc = [locations lastObject];
    
    
    //------------------位置反编码---5.0之后使用-----------------
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:cloc
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       
                       for (CLPlacemark *place in placemarks) {
                           
                           NSLog(@"name,%@",place.name);
                           // 位置名
                           //
                           NSLog(@"thoroughfare,%@",place.thoroughfare);
                           // 街道
                           //
                           NSLog(@"subThoroughfare,%@",place.subThoroughfare);
                           // 子街道
                           //
                           NSLog(@"locality,%@",place.locality);
                           // 市
                           //
                           NSLog(@"subLocality,%@",place.subLocality);
                           // 区
                           //
                           NSLog(@"country,%@",place.country);
                           // 国家
                       }
                       
                   }];
    
           [_locationManager stopUpdatingLocation];
        
        
}


0 0