如何获得ios 8中的当前位置?

时间:2015-04-30 05:23:21

标签: ios

我一直在研究ios8程序一段时间,我需要获取当前位置的源代码,如果你有这些请将其上传到一个zip文件中。

1 个答案:

答案 0 :(得分:0)

你需要为iOS8做以下事情:

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
-(void)viewDidLoad
{  
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];

self.locationManager.delegate = self;
if(IS_OS_8_OR_LATER){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] ||     [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
    // choose one request according to your business.
    if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
        [self.locationManager requestAlwaysAuthorization];
    } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
        [self.locationManager  requestWhenInUseAuthorization];
    } else {
        NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
    }
}
}
[self.locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {
    longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
}

您需要做两件额外的事情才能让位置正常工作:

在Info.plist中添加密钥 请求位置管理员要求其启动的授权。 需要在Info.plist文件中添加以下任何一个或两个键。

NSLocationWhenInUseUsageDescription NSLocationAlwaysUsageDescription 这些是String类型,值可以是任何消息描述或为空。

现在您需要请求相应位置方法的授权。使用以下任何一种电话:

[self.locationManager requestWhenInUseAuthorization] [self.locationManager requestAlwaysAuthorization]