iOS定位

来源:互联网 发布:tiger水杯 知乎 编辑:程序博客网 时间:2024/05/16 19:53

1.引入头文件

#import <CoreLocation/CoreLocation.h>

2.定义2个属性

@property (nonatomic, strong) CLLocationManager * locationManager;@property (nonatomic, strong) CLGeocoder * geocoder;

3.开始

- (IBAction)startLocation:(UIButton *)sender {    self.locationManager = [[CLLocationManager alloc] init];    self.locationManager.delegate = self;    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;    self.locationManager.distanceFilter = 100.0;    self.geocoder = [[CLGeocoder alloc] init];    if (![CLLocationManager locationServicesEnabled]) {        NSLog(@"定位服务不可用");        return;    } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {        [self.locationManager requestWhenInUseAuthorization];    } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {        [self.locationManager startUpdatingLocation];    } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {        self.locationManager = nil;    }}

4.代理方法

#pragma mark - CLLocationManagerDelegate- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {    CLLocation * loca = [locations firstObject];    [self.geocoder reverseGeocodeLocation:loca completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {        CLPlacemark * pm = placemarks[0];        self.cityLab.text = pm.locality;  //城市        [self.locationManager stopUpdatingLocation];    }];}//当定位状态发生改变时会调用- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {        [self.locationManager startUpdatingLocation];    } else if (status == kCLAuthorizationStatusDenied){        self.locationManager = nil;    }}

注意:iOS8以后,需要在plist文件加2个字段
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
如何对这2个key国际化?
xcode->File->New->File,选择String File,命名为InfoPlist.strings,然后对此文件国际化
第一句加入到中文Infoplist.strings,第二句加入到英文Infoplist.strings
“NSLocationWhenInUseUsageDescription” = “需要知道您跑了多少步”;
“NSLocationWhenInUseUsageDescription” = “Location is required to find out how many steps you run”;

0 0