原生手机定位教程

1、首先导入CoreLocation.framework这个依赖库,并在相应的控制器里导入头文件import


2、在info.plist文件里加入两个字段NSLocationWhenInUseUsageDescription,NSLocationAlwaysUsageDescription类型都是string类型的,如图

3、添加相应的协议 CLLocationManagerDelegate

4、下面就是代码部分

(1)、CLLocationManager * _locationManager;添加对象

(2)、初始化对象-(void)initializeLocationService{

_locationManager = [[CLLocationManager alloc] init];

// 设置代理

_locationManager.delegate = self;

// 设置定位精确度到米

_locationManager.desiredAccuracy = kCLLocationAccuracyBest;

// 设置过滤器为无

_locationManager.distanceFilter = kCLDistanceFilterNone;

// 开始定位

// 取得定位权限,有两个方法,取决于你的定位使用情况

// 一个是requestAlwaysAuthorization,一个是requestWhenInUseAuthorization

[_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。

[_locationManager startUpdatingLocation];

}

(3)、实现协议中的方法-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

[ProgressHUD show:nil];

NSString * locaton = [NSString stringWithFormat:@"经度%lf纬度%lf",newLocation.coordinate.longitude,newLocation.coordinate.latitude];

NSLog(@"我的位置%@",locaton);

CLGeocoder * geocoder = [[CLGeocoder alloc] init];

[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){

if (array.count > 0){

CLPlacemark *placemark = [array objectAtIndex:0];

//将获得的所有信息显示到label上

//获取城市

NSString *city = placemark.locality;

if (!city) {

//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

city = placemark.administrativeArea;

}

NSLog(@"city%@",city);

}

else if (error == nil && [array count] == 0)

{

NSLog(@"No results were returned.");

}

else if (error != nil)

{

NSLog(@"An error occurred = %@", error);

}

}];

[manager stopUpdatingLocation];

}

你可能感兴趣的:(原生手机定位教程)