找出是否启用了位置服务是行不通的

时间:2013-07-08 17:42:35

标签: ios objective-c cllocationmanager

我有一个使用设备位置的应用。如果他们允许该位置,我想运行我的方法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];
    ...
}

1 个答案:

答案 0 :(得分:3)

+ (CLAuthorizationStatus)authorizationStatus
  

返回值表示应用程序是否已获得授权的值   使用位置服务。

     

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

+ (BOOL)locationServicesEnabled
  

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

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

AuthorizationStatus应该检查状态:

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

但你在viewDidLoad方法中检查与bool值相等。

相关问题