CoreLocation功能强大,实际运用中常与地图结合使用,以达到地图显示与定位的功能。
(1)在info.plist文件中加入以下字段
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSLocationAlwaysUsageDescription</key>
<string>始终允许</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要使用您的定位功能</string>
(2)导入CoreLocation框架
(3)实现代码
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//检测定位功能是否开启
if ([CLLocationManager locationServicesEnabled]) {
if (!_locationManager) {
self.locationManager = [[CLLocationManager alloc]init];
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
//设置代理
self.locationManager.delegate = self;
//设置定位精度
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
//设置筛选距离
[self.locationManager setDistanceFilter:100];
//开始定位
[self.locationManager startUpdatingLocation];
//设置开始识别方向
[self.locationManager startUpdatingHeading];
}
}else {
//iOS9以后的UIAlertView
UIAlertController *aletController = [UIAlertController alertControllerWithTitle:@"您没有开启定位功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
[aletController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:aletController animated:YES completion:nil];
}
}
#pragma mark --CLLocationManagerDelegate--
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[self.locationManager stopUpdatingLocation];
CLLocation* location = locations.lastObject;
[self reverseGeocoder:location];
}
#pragma mark --Geocoder-
//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation {
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error || placemarks.count == 0) {
NSLog(@"error %@",error);
}else {
CLPlacemark *placemark = placemarks.firstObject;
NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"City"]);
UIAlertController *aletController = [UIAlertController alertControllerWithTitle:@"你的位置" message:[[placemark addressDictionary] objectForKey:@"City"] preferredStyle:UIAlertControllerStyleAlert];
[aletController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:aletController animated:YES completion:nil];
}
}];
}
@end