IOS 的定位已经不是很新鲜的了,定位共有三种方式,今天就其中的一种说一下,现在的版本中要多写上一句代码才可以完整的运行定位方法。此代码的意义是在第一次打开程序时提示用户是否允许该应用获取位置。
在开始写代码之前我们需要加入CoreLocation.framework这个框架!然后再ViewController.h中包含头文件
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
再加上一个代理
<CLLocationManagerDelegate>
-(void)viewWillAppear:(BOOL)animated
{
//开始定位
[_locationManager requestWhenInUseAuthorization]; //定位前需提示是否定位
[_locationManager startUpdatingLocation];
}
开始定位的方法写在这里只是为了打开程序就直接获取地理位置信息。
#pragma mark 实现位置更新
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
MYLog(@"纬度=%f 经度=%f 高度=%f",currLocation.coordinate.latitude,currLocation.coordinate.longitude,currLocation.altitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根据经纬度反向地理编译出地址信息
[geocoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *array, NSError *error)
{
if (array.count > 0)
{
CLPlacemark *placemark = [array objectAtIndex:0];
MYLog(@"%@",placemark.name);
//获取城市
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
NSLog(@"city = %@", city);
}
else if (error == nil && [array count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
}