0

我有一个使用设备位置的应用程序。如果他们允许该位置,我想运行我的方法getDataFromJson并正常运行我的应用程序。如果他们否认,或者以前否认过,我希望向他们展示一个视图,解释他们需要进入设置并允许它。

我有很多代码,但目前不起作用。谁能帮忙解释问题出在哪里?

非常感谢!

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([CLLocationManager authorizationStatus] == YES) {
        //are enabled, run the JSON request
        [self getDataFromJson];
    } else {
        //is not enabled, so set it up
        NSLog(@"no");
        [locationManager location];
    };

}

-(CLLocationCoordinate2D) getLocation{

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];
    return coordinate;

}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusDenied) {
        //location denied, handle accordingly
        locationFailView.hidden = NO;
        mainView.hidden = YES;
    }
    else if (status == kCLAuthorizationStatusAuthorized) {
        //hooray! begin tracking
        [self getDataFromJson];
    }
}

//class to convert JSON to NSData
- (IBAction)getDataFromJson {
    CLLocationCoordinate2D coordinate = [self getLocation];
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    ...
}
4

1 回答 1

3
+ (CLAuthorizationStatus)authorizationStatus

返回值 指示应用程序是否被授权使用位置服务的值。

讨论 给定应用程序的授权状态由系统管理并由几个因素决定。用户必须明确授权应用程序使用位置服务,并且当前必须为系统启用位置服务。当您的应用程序首次尝试使用位置服务时,此授权会自动进行。

+ (BOOL)locationServicesEnabled

返回一个布尔值,指示是否在设备上启用了位置服务。

您可以检查这两个状态:locationServicesEnabled 和 authorizationStatus 然后决定应该使用哪个方法。

AuthorizationStatus 应该检查状态:

typedef enum {
   kCLAuthorizationStatusNotDetermined = 0,
   kCLAuthorizationStatusRestricted,
   kCLAuthorizationStatusDenied,
   kCLAuthorizationStatusAuthorized
} CLAuthorizationStatus;

但是您在 viewDidLoad 方法中检查与 bool 值是否相等。

于 2013-07-08T18:18:53.807 回答