Разрешение местоположения iOS не работает, чтобы показать Objective C - PullRequest
0 голосов
/ 17 апреля 2019

Я создаю пример проекта для определения местоположения пользователя.
Но когда я запускаю приложение, разрешение на местоположение мне не показывается.
Что не так с моим кодом? Благодаря.

ViewController.h

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *latLabel;
@property (weak, nonatomic) IBOutlet UILabel *longLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.locationManager.delegate = self;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    CLLocation *currentLocation = [locations lastObject];
    if(currentLocation != nil){
        self.latLabel.text = [NSString stringWithFormat:@"%.2f",currentLocation.coordinate.latitude];
        self.longLabel.text = [NSString stringWithFormat:@"%.2f",currentLocation.coordinate.longitude];
        [self.locationManager stopUpdatingLocation];
    }
}

@end

enter image description here

enter image description here

enter image description here

1 Ответ

1 голос
/ 17 апреля 2019

Вам нужно начать с проверки locationServicesEnabled. Если они включены, перед вызовом authorizationStatus узнайте фактический статус авторизации вашего приложения. Вы запрашиваете диалог авторизации, только если статус «не определен».

Если статус - что-то еще, нет смысла спрашивать диалог авторизации; это не появится

Другая проблема в том, что этот код бесполезен:

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    CLLocation *currentLocation = [locations lastObject];
    if(currentLocation != nil){
        self.latLabel.text = [NSString stringWithFormat:@"%.2f",currentLocation.coordinate.latitude];
        self.longLabel.text = [NSString stringWithFormat:@"%.2f",currentLocation.coordinate.longitude];
        [self.locationManager stopUpdatingLocation];
    }
}

Вы звоните stopUpdatingLocation, как только вы получите первое обновление местоположения. Но шансы на получение полезного местоположения при первом обновлении местоположения first в основном равны нулю, поскольку датчики только разогреваются.

(Также обратите внимание, что проверять «Обновления местоположения» в фоновых режимах бессмысленно. Вы не получите никаких обновлений местоположения в фоновом режиме, если вы не установили для allowsBackgroundLocationUpdates диспетчера местоположений значение YES, и вы этого не делаете .)

...