1、导入框架
CoreLocation.framework
2、添加头文件
#import <CoreLocation/CoreLocation.h>
3、声明和代理
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong)CLLocationManager *locationManager;
@end
4、初始化
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = kCLDistanceFilterNone;
5、开始定位
- (void)startLocation {
if (IOS8) {
// 由于iOS8中定位的授权机制改变, 需要进行手动授权
[_locationManager requestAlwaysAuthorization];
[_locationManager requestWhenInUseAuthorization];
}
[_locationManager startUpdatingLocation];
}
6、代理回调
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
// 获取当前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根据经纬度反向地理编译出地址信息
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error)
{
if (array.count > 0) {
CLPlacemark *placemark = [array objectAtIndex:0];
//获取城市
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
NSLog(@"city = %@", city);
NSLog(@"dic = %@",placemark.addressDictionary);
} else if (error == nil && [array count] == 0) {
NSLog(@"No results were returned.");
} else if (error != nil) {
NSLog(@"An error occurred = %@", error);
}
}];
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
[manager stopUpdatingLocation];
NSString *errorString;
NSString *alterTitle;
NSLog(@"Error: %@",[error localizedDescription]);
switch([error code]) {
case kCLErrorDenied:
//Access denied by user
errorString = @"请在系统设置中开启定位服务\n(设置>隐私>定位服务)";
alterTitle = @"定位服务未开启";
break;
case kCLErrorNetwork:
//Probably temporary...
errorString = @"网络未开启,请检查网络设置";
alterTitle = @"提示";
break;
default:
errorString = @"发生位置错误";
alterTitle = @"提示";
break;
}
UIAlertView *locationFailAlert = [[UIAlertView alloc] initWithTitle:alterTitle message:errorString delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
[locationFailAlert show];
}
注意事项:
1、用户隐私的保护
在iOS8中,定位服务发生了变化,需要用户授权。
在工程info.plist文件中添加下面值:
<key>NSLocationUsageDescription</key>
<string>需要您的同意,才能访问位置</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要您的同意,才能在使用期间访问位置</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>需要您的同意,才能始终访问位置</string>
2、获取应用当前的定位服务状态
// 确定用户的位置服务是否启用
[CLLocationManager locationServicesEnabled]
// 位置服务是在设置中禁用
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
}