简体   繁体   English

获取iOS上的当前位置

[英]Get current location on iOS

I need to get current user location (latitude, longtitude), but I can not find a solution, because all solutions are just for iOS 6,7,8. 我需要获得当前用户位置(纬度,经度),但我找不到解决方案,因为所有解决方案都只适用于iOS 6,7,8。 For example, I have this code, but on iOS 11.3.1 it is still not working. 例如,我有这个代码,但在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];
}

From iOS 10 you need to add two keys to the info.plist as 从iOS 10开始,您需要将两个密钥添加到info.plist中

NSLocationAlwaysUsageDescription key to your Info.plist file. NSLocationAlwaysUsage描述Info.plist文件的密钥。 (Xcode displays this key as "Privacy - Location Always Usage Description" in the Info.plist editor.) (Xcode在Info.plist编辑器中将此密钥显示为“Privacy - Location Always Usage Description”。)

And for iOS 11 适用于iOS 11

Add the NSLocationWhenInUseUsageDescription key and the NSLocationAlwaysAndWhenInUseUsageDescription key to your Info.plist file. 将NSLocationWhenInUseUsageDescription键和NSLocationAlwaysAndWhenInUseUsageDescription键添加到Info.plist文件中。 (Xcode displays these keys as "Privacy - Location When In Use Usage Description" and "Privacy - Location Always and When In Use Usage Description" in the Info.plist editor.) (Xcode在Info.plist编辑器中将这些密钥显示为“隐私 - 使用时的位置使用说明”和“隐私 - 始终和使用时的位置使用说明”。)

Also find the complete guide at apple documentation at: apple corelocation authorization 另请参阅Apple文档中的完整指南: apple corelocation authorization

This is because you need to call one of these requestAlwaysAuthorization or requestWhenInUseAuthorization methods on your self.locationManager Object and add the keys accordingly to it in your App Plist. 这是因为您需要在self.locationManager对象上调用其中一个requestAlwaysAuthorizationrequestWhenInUseAuthorization方法,并在App Plist中相应地添加键。 Take a look . 看一看

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

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