3

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];
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Genevios
  • 1,115
  • 1
  • 16
  • 29

2 Answers2

4

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

Surbhi Garg
  • 414
  • 5
  • 19
3

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.

tryKuldeepTanwar
  • 3,490
  • 2
  • 19
  • 49