iOS_城市定位
技术点-利用CoreLoaction框架,实现城市定位功能。
原理:
利用苹果官方提供的CoreLocation框架实现城市定位的功能;
该框架主要包括两个比较有用的类:定位类CLLocationManager、地理编码类ClGeoCoder。
代码:
1 // Copyright © 2016年 刘勇虎. All rights reserved. 2 // 3 4 #import "ViewController.h" 5 #import <CoreLocation/CoreLocation.h> 6 7 @interface ViewController ()<CLLocationManagerDelegate> 8 @property(strong,nonatomic)CLLocationManager *locationMananger; 9 @property(strong,nonatomic)CLLocation *startPoint; 10 @property(strong,nonatomic)CLGeocoder *geoCode; 11 @property (weak, nonatomic) IBOutlet UILabel *cityName; 12 13 @end 14 15 @implementation ViewController 16 // 开始定位 17 - (IBAction)startLocationing:(UIButton *)sender { 18 [_locationMananger startUpdatingLocation]; 19 } 20 21 - (void)viewDidLoad { 22 [super viewDidLoad]; 23 // Do any additional setup after loading the view, typically from a nib. 24 25 26 _geoCode = [[CLGeocoder alloc]init]; 27 self.locationMananger = [[CLLocationManager alloc]init]; 28 _locationMananger.delegate = self; 29 _locationMananger.desiredAccuracy = kCLLocationAccuracyBest; 30 // 向系统申请权限 31 [_locationMananger requestWhenInUseAuthorization]; 32 33 34 } 35 36 #pragma mark -- location delegate -- 37 //更新定位 38 - (void)locationManager:(CLLocationManager *)manager 39 didUpdateToLocation:(CLLocation *)newLocation 40 fromLocation:(CLLocation *)oldLocation { 41 42 // 反地理编码 43 [_geoCode reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) { 44 if (placemarks && placemarks.count > 0) { 45 46 CLPlacemark *newPlaceMark = [placemarks firstObject]; 47 _cityName.text = newPlaceMark.locality; 48 [_locationMananger stopUpdatingLocation]; 49 } 50 }]; 51 } 52 //定位失败后回调 53 -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ 54 NSLog(@"error == %@",error); 55 }
修改info.Plist文件配置: