我创建了一个示例项目来获取用户位置。 但是当我运行应用程序时,位置权限不会显示给我。 我的代码出了什么问题?谢谢。
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,否则您不会在后台获得任何位置更新。您不会这样做。)