- And introducing a frame header CoreLocation
#import <CoreLocation/CoreLocation.h>
- Create a proxy object and set CLLocationManager
<CLLocationManagerDelegate>
// 初始化定位管理器
_locationManager = [[CLLocationManager alloc] init];
// 设置代理
_locationManager.delegate = self;
// 设置定位精确度到米
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 设置过滤器为无
_locationManager.distanceFilter = kCLDistanceFilterNone;
// 取得定位权限,有两个方法,取决于你的定位使用情况
// 一个是requestAlwaysAuthorization,一个是requestWhenInUseAuthorization
// 这句话ios8以上版本使用。
[_locationManager requestAlwaysAuthorization];
// 开始定位
[_locationManager startUpdatingLocation];
- In the above iOS8 system also you need to add the following key in the plist file to configure
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
Which can add their own value
-
If you want to turn on background location, then follow the steps below to set
Open backstage positioning .png
- We need to get to the location information of the corresponding proxy method
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
in this proxy method, we can obtain the current location of latitude and longitude
//获取经度
//self.longitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];
//获取维度
//self.latitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];
Obtain information about the current location of the city
// 获取当前所在的城市名
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;
}
NSArray *array = [city componentsSeparatedByString:@"市"];
NSString *cityStr = array[0];
NSString * cityEncode = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)cityStr, NULL, NULL, kCFStringEncodingUTF8 ));
//这里我把获取到的地址信息利用NSUserDefaults保存起来,后面会用到
NSMutableDictionary *dic = [NSMutableDictionary new];
[dic setValue:cityEncode forKey:@"city"];
[[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"cityName"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else if (error == nil && [array count] == 0) {
NSLog(@"没有结果返回.");
}
else if (error != nil) {
//NSLog(@"An error occurred = %@", error);
}
}];
- The system has been updated location data in the background, if you only need to get one stop information access to information updated after completion
[manager stopUpdatingLocation];