繁体   English   中英

iOS位置权限无法通过Objective-C显示

[英]iOS Location permission not work to show by Objective-C

我创建一个示例项目来获取用户位置。
但是,当我运行该应用程序时,位置权限未显示给我。
我的代码有什么问题? 谢谢。

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

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

您需要先检查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 但是,由于传感器正在预热,因此您在第一次位置更新中获得有用位置的机会基本上为零。

(还请注意,在后台模式下检查“位置更新”是没有意义的。除非将位置管理器的allowsBackgroundLocationUpdates为YES,否则您将不会在后台获得任何位置更新。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM