ios - iOS 位置权限无法由 Objective-C 显示
问题描述
我创建了一个示例项目来获取用户位置。
但是当我运行应用程序时,位置权限不会显示给我。
我的代码有什么问题?谢谢。
视图控制器.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
视图控制器.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
为“是”,否则您不会在后台获得任何位置更新,并且您没有这样做。)
推荐阅读
- python - 如何将数据输入到模型类的字段到html表?
- c# - 从服务调用 CloseMainWindow()
- javascript - 通过 Moment.js 以小时和分钟为单位的时差
- sockets - 所有 Socket 房间都会收到所有消息,即使它发送到一个房间
- linux - 循环遍历具有存储文件路径的文件并删除这些文件
- json - 从多个 json 文件中,将文档的关键字与另一个外部关键字列表匹配。并返回匹配关键字的文件?
- c# - 播放器碰撞时制作加载屏幕(不起作用)
- ios - 在 scrollableStack 中处理选中的 UIView
- node.js - 从重定向 URL 检索授权码
- c++ - 如何对具有 NA 值的向量进行排序,并将 NA 值放在 Rcpp 或 C++ 中结果的末尾?