参考地址:
http://www.jianshu.com/p/ef6994767cbb
http://www.jianshu.com/p/f58be9373b6a
- (void)initLocationManager {
if ([CLLocationManager locationServicesEnabled]) {
if (self.locationManager == nil){
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.locationManager.distanceFilter = 1.0;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization]; // 永久授权
[self.locationManager requestWhenInUseAuthorization]; //使用中授权
}
[self.locationManager startUpdatingLocation];//开启位置更新
}
}
// 实现代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation * currentLocation = [locations lastObject];
if (currentLocation != nil) {
[self.locationManager stopUpdatingLocation]; // 停止定位
}
double altitude = currentLocation.altitude; // 高度
double latitude = currentLocation.coordinate.latitude;
double longitude = currentLocation.coordinate.longitude;
NSLog(@"altitude:%f, latitude: %f, longitude:%f", altitude, latitude, longitude)
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"%@", error);
if (error.code == kCLErrorDenied) {
NSLog(@"%@", error);
}
}
ios8中需要配置键 info.plist 中加入以下键值
<key>NSLocationWhenInUseUsageDescription</key>
<string>请允许GPS定位,获取更好的体验效果</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>请允许GPS定位,获取更好的体验效果</string>
key的数据类型据测试结果好像string(一段字符串描述) 和 bool( YES)类型 都可以定位的