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
新聞熱點
疑難解答