現在的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;
}];
}
可以根據自己的需求再做封裝吧,畢竟每個人的習慣都不一樣!