Обработка разрешения местоположения в iOS Цель C - PullRequest
0 голосов
/ 11 мая 2018

Я хочу проверить, включены ли службы определения местоположения пользователя после или нет пользователя Разрешить или Запретить разрешение на местоположение. Я проверил в методе viewdidload разрешение, но оно появляется до того, как пользователь установил разрешение, Я хотел запустить этот код после того, как пользователь установил разрешение Location (Разрешить или Не Разрешить) из всплывающего окна разрешения на устройстве. Объектив c

- (Недействительными) viewDidLoad

if(status==kCLAuthorizationStatusAuthorizedWhenInUse) {
        float latitude;
        float longitude;
        CLLocationCoordinate2D coordinate = [self myLocation];
        latitude = coordinate.latitude;
        longitude = coordinate.longitude;
        status = [CLLocationManager authorizationStatus];

    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

    CLGeocoder*myGeocoder = [[CLGeocoder alloc] init];

    [myGeocoder
     reverseGeocodeLocation:location
     completionHandler:^(NSArray *placemarks, NSError *error) {

         if (error == nil && placemarks.count > 0){

             CLPlacemark *placemark = placemarks[0];
             if ([placemark.locality isEqualToString:@"Mumbai"]) {
                 NSLog(@"Location is Mumbai");
             }
             else{
                 if (placemark.locality) {
                     alert=[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"This app is not available @%@",placemark.locality] preferredStyle:UIAlertControllerStyleAlert];
                     [self presentViewController:alert animated:YES completion:nil];
                 }
                 else{
                     alert=[UIAlertController alertControllerWithTitle:nil message:@"This app is not available at your location" preferredStyle:UIAlertControllerStyleAlert];
                     [self presentViewController:alert animated:YES completion:nil];
                 }
             }


         }
         else if (error == nil && placemarks.count == 0){
             NSLog(@"No results were returned.");
         }
         else if (error != nil) {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}
else{

    alert=[UIAlertController alertControllerWithTitle:@"Location Permission" message:@"To re-enable, please go to Settings and turn on Location Service for this app." preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *Retry=[UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        exit(0);
    }];
    [alert addAction:Retry];
    [self presentViewController:alert animated:YES completion:nil];
}

1 Ответ

0 голосов
/ 11 мая 2018

Сначала включите делегата:

CLLocationManagerDelegate

Объявление свойства:

@ свойство (сильное, неатомное) CLLocationManager * locationManager;

В поле зрения загрузки добавлено следующее:

if( _locationManager == nil )
    {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [_locationManager startUpdatingLocation];
    }

[self checkLocationAccess];

И метод checkLocationAccess:

- (void)checkLocationAccess {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {

    // custom methods after each case

        case kCLAuthorizationStatusDenied:
            [self allowLocationAccess]; // custom method
            break;
        case kCLAuthorizationStatusRestricted:
            [self allowLocationAccess]; // custom method
            break;
        case kCLAuthorizationStatusNotDetermined:
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            break;
    }
}

Метод наблюдателя:

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        NSLog(@"allowed"); // allowed
    }
    else if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"denied"); // denied
    } 
}
...