Search code examples
iosobjective-cmkmapviewcllocationmanager

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];
}

Solution

  • 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