1.首先在plist文件中添加
<key>NSLocationWhenInUseUsageDescription</key><string>需要定位</string>
<key>NSLocationAlwaysUsageDescription</key><string>需要定位</string>
2.之后在Build Phases 中的Link Binary With Libraries 中添加 CoreLoaction.framework
3.在需要调取的地方引入#import <CoreLocation/CoreLocation.h> 以及<CLLocationManagerDelegate>代理
下面是具体方法
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
NSString * currentCity; //当前城市
}
@end
@implementation ViewController
- (void)locate {
//判断定位功能是否打开
if ([CLLocationManager locationServicesEnabled]) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// [locationManager requestAlwaysAuthorization];
currentCity = [[NSString alloc] init];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
[locationManager requestWhenInUseAuthorization]; //调用了这句,就会弹出允许框了.
}
[locationManager startUpdatingLocation];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self locate];
};
//定位失败则执行此代理方法
//定位失败弹出提示框,点击"打开定位"按钮,会打开系统的设置,提示打开定位服务
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"允许\"定位\"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//打开定位设置
// NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
// [[UIApplication sharedApplication] openURL:settingsURL];
}];
UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alertVC addAction:cancel];
[alertVC addAction:ok];
[self presentViewController:alertVC animated:YES completion:nil];
}
//定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
[locationManager stopUpdatingLocation];
CLLocation *currentLocation = [locations lastObject];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
//反编码
[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (placemarks.count > 0) {
CLPlacemark *placeMark = placemarks[0];
currentCity = placeMark.locality;
if (!currentCity) {
currentCity = @"无法定位当前城市";
}
NSLog(@"%@",currentCity); //这就是当前的城市
NSLog(@"%@",placeMark.name);//具体地址: xx市xx区xx街道
}
else if (error == nil && placemarks.count == 0) {
NSLog(@"No location and error return");
}
else if (error) {
NSLog(@"location error: %@ ",error);
}
}];
}
@end