现在的app应用,几乎每个应用都带有定位功能,利用苹果自带的api就可以很快的实现定位功能,当然还要在info.plist文件中配置定位权限(自行脑补吧,ios10好像每个权限,不管你用了没,都要配置,不用上架都不让你上)。下面的代码是我从工具类中抽取出来的,作为参考。
#pragma mark 定位------------------------------------------------
#pragma mark - 初始化定位管理器并开始定位
- (void)startLocationWithBlock:(successBlock)success
{
_locationSuccess = success;
//定位管理器
_locationManager = [[CLLocationManager alloc] init];
_geocoder = [[CLGeocoder alloc] init];
if (![CLLocationManager locationServicesEnabled])
{
[_myAlertView myAlertView:@"定位服务没有打开!请到“设置->隐私->定位服务”中打开定位服务。" andButtonText:@"确定"];
return;
}
//如果没有授权则请求用户授权
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)
{
[_locationManager requestWhenInUseAuthorization];
}
else if([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusAuthorizedWhenInUse)
{
//设置代理
_locationManager.delegate = self;
//设置定位精度
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//启动跟踪定位
[_locationManager startUpdatingLocation];
}
}
#pragma mark 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)
//可以通过模拟器设置一个虚拟位置,否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations firstObject]; //取出第一个位置
CLLocationCoordinate2D coordinate = location.coordinate; //位置坐标
//NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
// 根据坐标位置进行反地理编码
[self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
//如果不需要实时定位,使用完即使关闭定位服务
[_locationManager stopUpdatingLocation];
}
#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
{
//反地理编码
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error){
CLPlacemark *placemark = [placemarks firstObject];
NSLog(@"City:%@", placemark.addressDictionary[@"City"]);
NSLog(@"Country:%@", placemark.addressDictionary[@"Country"]);
NSLog(@"CountryCode:%@", placemark.addressDictionary[@"CountryCode"]);
NSLog(@"FormattedAddressLines:%@", placemark.addressDictionary[@"FormattedAddressLines"][0]);
NSLog(@"Name:%@", placemark.addressDictionary[@"Name"]);
NSLog(@"State:%@", placemark.addressDictionary[@"State"]);
NSLog(@"Street:%@", placemark.addressDictionary[@"Street"]);
NSLog(@"SubLocality:%@", placemark.addressDictionary[@"SubLocality"]);
NSLog(@"Thoroughfare:%@", placemark.addressDictionary[@"Thoroughfare"]);
NSDictionary *dict = @{@"addressStr":[NSString stringWithFormat:@"%@%@%@", placemark.addressDictionary[@"City"], placemark.addressDictionary[@"SubLocality"], placemark.addressDictionary[@"Street"]], @"lat":[NSNumber numberWithDouble:latitude], @"lng":[NSNumber numberWithDouble:longitude]};
_locationSuccess(dict);
_locationSuccess = nil;
}];
}
可以根据自己的需求再做封装吧,毕竟每个人的习惯都不一样!