首先在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 {
[super viewDidLoad];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服务没有打开");
return;
}
//2.判断程序是否允许使用定位
CLLocationManager *mgr=[[CLLocationManager alloc] init];
self.manager=mgr;
if ([CLLocationManager authorizationStatus]!=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];
}
本文介绍如何在iOS应用中实现定位服务,包括权限设置、位置更新及反编码获取详细地址信息等关键技术点。
1万+

被折叠的 条评论
为什么被折叠?



