CLLocationManagerDelegate
#pragma mark 定位
-(void)locate
{
// 判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
locationManager = [[CLLocationManager alloc] init] ;//创建位置管理器
[locationManager requestAlwaysAuthorization]; //NSLocationAlwaysUsageDescription
[locationManager requestWhenInUseAuthorization]; //NSLocationWhenInUseDescription
locationManager.delegate = self;
//desiredAccuracy为设置定位的精度,可以设为最优,装置会自动用最精确的方式去定位。
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
locationManager.distanceFilter=1000.0;
// 开始定位
[locationManager startUpdatingLocation];
}else {
NSLog(@"定位请求被拒绝");
-(void)locate
{
// 判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
locationManager = [[CLLocationManager alloc] init] ;//创建位置管理器
[locationManager requestAlwaysAuthorization]; //NSLocationAlwaysUsageDescription
[locationManager requestWhenInUseAuthorization]; //NSLocationWhenInUseDescription
locationManager.delegate = self;
//desiredAccuracy为设置定位的精度,可以设为最优,装置会自动用最精确的方式去定位。
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
locationManager.distanceFilter=1000.0;
// 开始定位
[locationManager startUpdatingLocation];
}else {
NSLog(@"定位请求被拒绝");
}
}
#pragma mark 定位代理
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
}
#pragma mark 定位代理
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
CLLocation *currentLocation = [locations lastObject];
// 获取当前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"%@",placemark.name);
//获取城市
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
NSLog(@"city = %@", city);
}
else if (error == nil && [placemarks count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
[locationManager stopUpdatingLocation];
}];
}