1.导入系统框架
import <CoreLocation/CoreLocation.h>
实现CLLocationManagerDelegate协议
声明位置管理对象属性
@property (nonatomic, strong) CLLocationManager *locationManager;
2.初始化CLLocationManager对象获取位置信息
-(void)initLocation
{
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
// 设置定位精度
[_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
// 请求用户权限:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
// 只在前台开启定位
[_locationManager requestWhenInUseAuthorization];
// 在后台也可定位
// [_locationManager requestAlwaysAuthorization];
}
// 更新用户位置
[_locationManager startUpdatingLocation];
}
3.定位权限变化通知
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined:
{
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
NSLog(@"用户还未决定授权");
break;
}
case kCLAuthorizationStatusRestricted:
{
NSLog(@"访问受限");
// 通过 ip 获取位置信息
break;
}
case kCLAuthorizationStatusDenied:
{
// 类方法,判断是否开启定位服务
if ([CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服务开启,被拒绝");
} else {
NSLog(@"定位服务关闭,不可用");
}
break;
}
case kCLAuthorizationStatusAuthorizedAlways:
{
// NSLog(@"获得前后台授权");
break;
}
case kCLAuthorizationStatusAuthorizedWhenInUse:
{
// NSLog(@"获得前台授权");
break;
}
default:
break;
}
}
4.用户位置信息变化回调
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
if (locations && [locations count] > 0) {
CLLocation *newLocation = locations[0];
//CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
[manager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (placemarks && [placemarks count] > 0) {
// 纬度
CLLocationDegrees latitude = newLocation.coordinate.latitude;
// 经度
CLLocationDegrees longitude = newLocation.coordinate.longitude;
NSString *cityName = @"火星";
for (CLPlacemark *place in placemarks) {
if (place.locality.length > 0) {
cityName = place.locality;
}
}
}
}];
}
}
5.如果用户拒绝访问位置信息,这时可以通过访问淘宝 ip 获取ip地址信息
http://ip.taobao.com/service/getIpInfo.php?ip=myip
网友评论