简体   繁体   中英

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. For example, I have this code, but on iOS 11.3.1 it is still not working.

#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

NSLocationAlwaysUsageDescription key to your Info.plist file. (Xcode displays this key as "Privacy - Location Always Usage Description" in the Info.plist editor.)

And for iOS 11

Add the NSLocationWhenInUseUsageDescription key and the NSLocationAlwaysAndWhenInUseUsageDescription key to your Info.plist file. (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.)

Also find the complete guide at apple documentation at: 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. Take a look .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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