为什么我允许后才使用位置服务?

时间:2014-09-04 23:53:45

标签: ios objective-c core-location cllocationmanager

在我的iOS应用程序中,我有一个表格,它使用您的位置来查找您附近的数据。我今天刚刚将它安装在我的iPhone上,当需要定位服务时,我得到了预期的警告“MyAppName想要使用你当前的位置”,一旦我按下OK,该应用程序基本冻结了。当我关闭应用程序并重新打开它时,它工作得非常好。现在我想到了,这也发生在模拟器上,因为我必须在位置服务正常工作之前运行应用程序几次。这是否发生在其他任何人身上,你知道如何解决这个问题吗?我不希望我的用户必须关闭应用程序并重新打开它以使位置服务正常工作。

以下是一些相关代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"%@",error.userInfo);
    if([CLLocationManager locationServicesEnabled]){
        NSLog(@"Location Services Enabled");
        UIAlertView    *alert = [[UIAlertView alloc] initWithTitle:@"Need Your Location"
                                                           message:@"Please go to Settings and turn on Location Services so you can see who's near you."
                                                          delegate:nil
                                                 cancelButtonTitle:@"OK"
                                                 otherButtonTitles:nil];
        [alert show];
    }
}

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

    if (currentLocation != nil) {
        _thisGeoPoint = [PFGeoPoint geoPointWithLatitude:currentLocation.coordinate.latitude
                                           longitude:currentLocation.coordinate.longitude];
    }
    [locationManager stopUpdatingLocation];
    located = true;
}

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为当locationManager最初没有权限时会停止运行。因此,一旦检测到权限已更改,您将需要重新运行它。您可以使用didChangeAuthorizationStatus delegate method检查权限是否已更改。

这样的事情:

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusAuthorized) {
        [locationManager startUpdatingLocation];
    }
}