項(xiàng)目當(dāng)中經(jīng)常使用到需要獲取用戶的地理位置窖杀,經(jīng)緯度守屉,現(xiàn)在使用CLLocationManager 蘋果自帶的獲取地理位置的方法
引入頭文件讥邻,8.0之后不用添加庫(kù)拦英,之前需要添加庫(kù)
#import<CoreLocation/CoreLocation.h>
設(shè)置代理<CLLocationManagerDelegate>
設(shè)置info.plist蜒什,添加其中一個(gè)就行,
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description?
@property(nonatomic,strong)CLLocationManager*manger;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.manger=[[CLLocationManageralloc]init];
_manger.delegate=self;
//開(kāi)始定位疤估,灾常,,铃拇,
[_mangerstartUpdatingLocation];
//可以設(shè)置在使用是定位也可以設(shè)置一直定位钞瀑,根據(jù)項(xiàng)目需求
[_mangerrequestWhenInUseAuthorization];
}
//實(shí)現(xiàn)代理方法
//第一次安裝會(huì)彈出授權(quán)界面,如果不允許定位慷荔,在下面的方法里可以自動(dòng)跳轉(zhuǎn)設(shè)置頁(yè)面雕什,更改完設(shè)置頁(yè)面,回到app會(huì)重新走這個(gè)方法显晶,不用手動(dòng)調(diào)用
- (void)locationManager:(CLLocationManager*)manager
didUpdateLocations:(NSArray *)locations{
//獲取定位的最后一組數(shù)據(jù)贷岸,
/* locations.lastObject存儲(chǔ)的數(shù)據(jù),包括經(jīng)緯度吧碾,定位時(shí)間凰盔,
<+34.25024365,+108.99842144> +/- 65.00m (speed -1.00 mps / course -1.00) @ 2017/8/25 \U4e2d\U56fd\U6807\U51c6\U65f6\U95f4 \U4e0a\U534811:11:02"
*/
CLLocation*location = locations.lastObject;
//返回當(dāng)前的經(jīng)緯度
CLLocationCoordinate2Dcoordinate = location.coordinate;
NSLog(@"獲取經(jīng)緯度::%.2f,,,,,,%.2f",coordinate.latitude,coordinate.longitude);
//反地理編碼墓卦,通過(guò)定位可以獲取當(dāng)前的城市
CLGeocoder*gecoder = [[CLGeocoderalloc]init];
[gecoderreverseGeocodeLocation:locationcompletionHandler:^(NSArray *_Nullableplacemarks,NSError*_Nullableerror) {
CLPlacemark*mark = [placemarksfirstObject];
NSLog(@"%@倦春,,time %@,,,ddress::%@",mark,mark.timeZone,mark.addressDictionary);
}];
//停止定位
[self.mangerstopUpdatingLocation];
//停止定位反地理編碼也不再執(zhí)行
//[gecoder cancelGeocode];
}
//這是通過(guò)方法去實(shí)現(xiàn)自動(dòng)打開(kāi)設(shè)置頁(yè)面,獲取定位權(quán)限的睁本,返回app會(huì)重新走這個(gè)代理方法尿庐,didUpdateLocations方法。
- (IBAction)locationBtn:(id)sender {
//[self.manger startUpdatingLocation];
NSURL* url = [NSURLURLWithString:UIApplicationOpenSettingsURLString];
if([[UIApplicationsharedApplication]canOpenURL:url]) {
NSURL*url =[NSURLURLWithString:UIApplicationOpenSettingsURLString];
[[UIApplicationsharedApplication]openURL:url];
}
}