0.配置info 添加 NSLocationAlwaysUsageDescription这个东东。
1.需要库CoreLocation.framework。
2.声明 #import <CoreLocation/CoreLocation.h>(注意加入CLLocationManagerDelegate代理)
3.代码实现
// 判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}else {
//提示用户无法进行定位操作
}
if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[_locationManager requestAlwaysAuthorization];
}
//开始定位,不断调用其代理方法
[_locationManager startUpdatingLocation];
4.代理回调定位结果
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
// 1.获取用户位置的对象
CLLocation *location = [locations lastObject];
CLLocationCoordinate2D coordinate = location.coordinate;
NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
strLongitude = [NSString stringWithFormat:@"%f",coordinate.longitude];
strLatitude = [NSString stringWithFormat:@"%f",coordinate.latitude];
// 2.停止定位
[manager stopUpdatingLocation];
}
网友评论