iOS 定位(CoreLocation)
2017-01-29 本文已影响59人
DH_Fantasy
在很多LBS的应用中我们都可以看到定位的使用。如下面美团外卖选择城市的页面。
美团外卖选择城市页下面我们就实现一个定位Demo,并将获取到的定位城市展示到页面上。
iOS系统已经封装了一个用于定位的类库CoreLocation,我们只需要将其头文件导入。要想使用定位服务,首先需要实例化一个CLLocationManager对象并设置Delegate。
- (void)initLocationManager{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
self.locationManager.distanceFilter=10;
if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];//开启定位
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *currLocation=[locations lastObject];
NSLog(@"latitude---%f, longitude---%f",currLocation.coordinate.latitude,currLocation.coordinate.longitude);
CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
[clGeoCoder reverseGeocodeLocation:currLocation completionHandler: ^(NSArray *placemarks,NSError *error) {
NSLog(@"--array--%d---error--%@",(int)placemarks.count,error);
if (placemarks.count > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *city = placemark.administrativeArea;
NSLog(@"位于:%@",city);
NSLog(@"%@",placemark.addressDictionary[@"Name"]);
}
}];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
if ([error code]==kCLErrorDenied) {
NSLog(@"访问被拒绝");
}
if ([error code]==kCLErrorLocationUnknown) {
NSLog(@"无法获取位置信息");
}
}
联系作者:简书·DH_Fantasy 新浪微博·DH_Fantasy
版权声明:自由转载-非商用-非衍生-保持署名(CC BY-NC-ND 3.0)