Adèle Dunand Adèle Dunand - 6 months ago 22
Objective-C Question

Location authorization issue in Objective C

I have an issue showing user locations in objective C.
I tried everything i could find here in stackoverflow, aaaand, didn't work.

So I have that code :

-(void)setLocation
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
MKPointAnnotation *myAnnotation = [[MKPointAnnotation alloc]init];


locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 10.0;
[locationManager startUpdatingLocation];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];



myAnnotation.coordinate = mapView.userLocation.location.coordinate;

myAnnotation.title = @"Test";
myAnnotation.subtitle = @"I am a test Subtitle";

[self.mapView addAnnotation:myAnnotation];
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
[self.mapView setCenterCoordinate:userLocation.coordinate animated:YES];
}


Everything is in ViewController.m, more precisely in a mapView declared in my .h file:

@property (strong, nonatomic) IBOutlet MKMapView *mapView;


Does anyone have any idea ? The error i have is that:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.


Thanks :)

Answer

I can't post this as a comment so i'll post it here.

You can simply open your Info.plist file in TextEdit and add these lines.

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
    <string>external-accessory</string>
    <string>remote-notification</string>
</array>
<key>NSLocationUsageDescription</key>
<string>App needs to use GPS to keep track of your activity</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App needs to use GPS to keep track of your activity</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>armv7</string>
    <string>gps</string>
</array>

EDIT:

I see that your locationManager is a local method variable. It should declared be as an instance variable or as a property.