Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] error

This is my code, showing both the alert and the blue dot for the current position on the map:

MapName.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>


@interface MapName : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>

@property (strong, nonatomic) IBOutlet MKMapView *MapName;
@property (strong, nonatomic) CLLocationManager *locationManager;

@end

MapName.m

- (void)viewDidLoad
{
[super viewDidLoad];

self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    [self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];

//Center the map
[self gotoLocation];

//Show current position
_MapName.showsUserLocation = YES;

}

I've added the key NSLocationWhenIsUseUsageDescription as a string to the Info.plist. I'm still getting the same error on Xcode.

like image 329
Max1980 Avatar asked Sep 20 '14 15:09

Max1980


2 Answers

It is due to both:

[self.locationManager startUpdatingLocation];

and

_MapName.showsUserLocation = YES;

You need to check if the user has given permission before you call these. Also make sure you turn off User Location in the MKMapKit on the storyboard (this one took me days to track down).

Do something like:

CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];

if (authorizationStatus == kCLAuthorizationStatusAuthorized ||
    authorizationStatus == kCLAuthorizationStatusAuthorizedAlways ||
    authorizationStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {

    [self.locationManager startUpdatingLocation];       
    _MapName.showsUserLocation = YES;        

}

Depending on your app you may not want to ask for the user's permission on launch since that is not recommended.

like image 62
jjmias Avatar answered Oct 20 '22 14:10

jjmias


The error message is pretty literal. Don't call [self.locationManager startUpdatingLocation] until you have authorization. Your [self.locationManager requestWhenInUseAuthorization], per the docs, is asynchronous.

When the current authorization status is kCLAuthorizationStatusNotDetermined, this method runs asynchronously and prompts the user to grant permission to the app to use location services.

This means you are both prompting for access as well as starting your scan at the same time.

Instead, try implementing -[CLLocationManagerDelegate locationManager:didChangeAuthorizationStatus:] and starting your scan there after it's been determined that you have authorization.

like image 38
incanus Avatar answered Oct 20 '22 14:10

incanus