我创建了一个示例项目来获取用户位置。
但是当我运行该应用程序时,位置权限未显示给我。
我的代码有什么问题?
谢谢。
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
答案 0 :(得分:1)
您需要先检查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];
}
}
您首先获得{em> first 位置更新,就会致电stopUpdatingLocation
。但是,由于传感器正在预热,因此在 first 位置更新中获得有用位置的机会基本上为零。
(还请注意,在后台模式下检查“位置更新”是没有意义的。除非将位置管理器的allowsBackgroundLocationUpdates
设置为YES,否则您将不会在后台获得任何位置更新。这样。)