获取iOS上的当前位置

时间:2018-05-03 10:03:02

标签: ios objective-c mkmapview cllocationmanager

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

2 个答案:

答案 0 :(得分:4)

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

  

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

适用于iOS 11

  

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

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

答案 1 :(得分:3)

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