繁体   English   中英

获取iOS上的当前位置

[英]Get current location on iOS

我需要获得当前用户位置(纬度,经度),但我找不到解决方案,因为所有解决方案都只适用于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];
}

从iOS 10开始,您需要将两个密钥添加到info.plist中

NSLocationAlwaysUsage描述Info.plist文件的密钥。 (Xcode在Info.plist编辑器中将此密钥显示为“Privacy - Location Always Usage Description”。)

适用于iOS 11

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

另请参阅Apple文档中的完整指南: apple corelocation authorization

这是因为您需要在self.locationManager对象上调用其中一个requestAlwaysAuthorizationrequestWhenInUseAuthorization方法,并在App Plist中相应地添加键。 看一看

暂无
暂无

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

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