1.添加CoreLocation.framework
2.info.plist添加
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
如果不需要提示什么值为空就行
3.因为对OC不熟悉所以将就看吧
#import <CoreLocation/CoreLocation.h>
@class RootViewController;
@interface AppController : NSObject <UIApplicationDelegate,CLLocationManagerDelegate>
{
UIWindow *window;
RootViewController *viewController;
CLLocationManager *_locationManager;
NSInteger _locationCount;
}
- (void)startLocation;
@end
- (void)startLocation{
if([CLLocationManager locationServicesEnabled]){
//获取定位
_locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 设置过滤器为无
_locationManager.distanceFilter = kCLDistanceFilterNone;
// 一个是requestAlwaysAuthorization,一个是requestWhenInUseAuthorization
// 这句话ios8以上版本使用。
[_locationManager requestWhenInUseAuthorization];
[_locationManager startUpdatingLocation];
_locationCount = 0;
}else{
NSLog(@"no open location service!!!");
}
}
//实现CLLocationManagerDelegate的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if (_locationCount > 0) {
return;
}
CLLocation *currLocation = [locations lastObject];
// NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
//此方法虽然停止了但还是会多次调用要注意
[manager stopUpdatingLocation];
// 保存 Device 的现语言 (英语 法语 ,,,)
NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
// 强制 成 简体中文
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans",nil,nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
//创建地理位置解码编码器对象
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
for (CLPlacemark * place in placemarks) {
// NSLog(@"国家:%@",place.country);
// NSLog(@"国家:%@",place.administrativeArea);
// NSLog(@"城市:%@",place.locality);
// NSLog(@"区:%@",place.subLocality);
// NSLog(@"街道:%@",place.thoroughfare);
// NSLog(@"子街道:%@",place.subThoroughfare);
}
// 还原Device 的语言
[[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];
}];
_locationCount = _locationCount + 1;
}
//获取用户位置数据失败的回调方法,在此通知用户
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if ([error code] == kCLErrorDenied)
{
//访问被拒绝
NSLog(@"访问被拒绝");
}
if ([error code] == kCLErrorLocationUnknown) {
//无法获取位置信息
NSLog(@"无法获取位置信息");
}
[_locationManager stopUpdatingLocation];//关闭定位
}
遇到的问题一个是系统语言是英文的获取到的位置都是英文,需要设置变成中文再还原,此处有个注意的地方还原Device 的语言的代码位置,以前写在completionHandler外面一直不好用;
网友评论