您的位置:首页 > 移动开发 > IOS开发

IOS 8 基本定位实现

2015-10-15 20:03 471 查看
首先在项目中导入定位所需的库,Build Phases --> Link Binary With Libraries -->CoreLocation.framework

在Info.plist文件中加入字段NSLocationWhenInUseUsageDescription或者NSLocationAlwaysUsageDescription,前者是应用使用时可定位,后者是后台可定位,根据需要设置,并设置为YES

其次在AppDelegate.m中导入所需头文件,并且遵循定位协议

#import <CoreLocation/CoreLocation.h>
@interface AppDelegate ()<CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@end

可以编写一个函数启动定位,并在didFinishLaunchingWithOptions中调用

- (void)startingLocation {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 10.0f;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager startUpdatingLocation];
}

实现定位协议方法didUpdateLocations和didFailWithError

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// 如果需要多次定位则不要此句
[self.locationManager stopUpdatingLocation];

CLLocation *curLocation = [locations lastObject];
// 所在位置经纬度
NSString *latitude = [NSString stringWithFormat:@"%f", curLocation.coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", curLocation.coordinate.longitude];
// 根据经纬度获得当前城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:curLocation completionHandler:^(NSArray *array, NSError *error) {
if (array.count > 0) {
CLPlacemark *placeMark = [array objectAtIndex:0];
NSString *city = placeMark.locality;
// 直辖市可能需要通过以下判断获取
if (!city) {
city = placeMark.administrativeArea;
}
LogBlue(@"定位城市:%@", city);
}else if (error == nil && [array count] == 0) {
LogRed(@"%@", @"无任何信息");
}else if (error != nil) {
LogRed(@"%@", @"定位错误");
LogRed(@"%@", error);
}
}];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"%@", error);
if ([error code] == kCLErrorDenied) {
// 访问被拒绝
LogRed(@"访问被拒绝");
}else if ([error code] == kCLErrorLocationUnknown) {
// 无法获取位置信息
LogRed(@"无法获取位置信息");
}
}

最后,如果只需要经纬度怎不需要逆地址解析,如果需要城市名要注意获得的城市后面带有“市”,需根据需求自行处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IOS8 定位