在iOS上获取当前位置

3

我需要获取当前用户的位置(纬度,经度),但我找不到解决方案,因为所有的解决方案都只适用于iOS 6、7、8。例如,我有这段代码,但在iOS 11.3.1上仍然无法工作。

#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *latitudeValue;
@property (weak, nonatomic) IBOutlet UILabel *longtitudeValue;

@property (nonatomic,strong) CLLocationManager *locationManager;

- (void)viewDidLoad
{
    [super viewDidLoad];

    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager startUpdatingLocation];
    } else {
        NSLog(@"Location services are not enabled");
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    self.latitudeValue.text = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
    self.longtitudeValue.text = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
}

委托是否被调用 - Anbu.Karthik
2个回答

4

iOS 10及以上版本需要在info.plist文件中添加两个密钥:

NSLocationAlwaysUsageDescription密钥。 (在Info.plist编辑器中,Xcode将此密钥显示为“隐私-始终使用位置说明”)

而对于iOS 11:

需要在Info.plist文件中添加NSLocationWhenInUseUsageDescription密钥和NSLocationAlwaysAndWhenInUseUsageDescription密钥。 (在Info.plist编辑器中,Xcode将这些密钥显示为“隐私-使用时使用位置说明”和“隐私-始终和使用时使用位置说明”)

同时,在苹果文档apple corelocation authorization中可以找到完整的指南。


3
这是因为您需要在 self.locationManager 对象上调用其中一个方法 requestAlwaysAuthorizationrequestWhenInUseAuthorization,并在您的应用程序 Plist 中相应地添加密钥。看一下

1
很高兴能帮到你 #随时准备帮忙 :) - tryKuldeepTanwar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接