How can I get permission from the user to access location service from a non UI class (iOS 8 and above)? No matter what I do - requestWhenInUseAuthorization
doesn't alert the user. I'm using objective c.
I have added the key in the plist file as well.
LocationController.h
@interface LocationController : NSObject <CLLocationManagerDelegate>{
BOOL _debug;
}
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *location;
- (id)initWithDebug:(BOOL)debug_flag;
@end
LocationController.m
@implementation LocationController {
}
@synthesize debug, locationManager, location;
#define IOS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
- (id)initWithDebug:(BOOL)debug_flag {
self = [super init];
if (self) {
[self findLocation];
}
return self;
}
-(void) findLocation{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self checkLocationPermissions];
self.location = self.locationManager.location;
}
-(void)checkLocationPermissions {
if ([CLLocationManager locationServicesEnabled]) {
if (IOS_8_OR_LATER) {
[self.locationManager requestWhenInUseAuthorization];
} else {
[self.locationManager startUpdatingLocation];
}
}
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
[self.locationManager startUpdatingLocation];
} break;
case kCLAuthorizationStatusDenied: {
[self.locationManager stopUpdatingLocation];
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
[self.locationManager startUpdatingLocation];
} break;
default:
break;
}
}
@end
EDIT: The code reaches till [self.locationManager requestWhenInUseAuthorization]; but never shows the alert.
This code is called from a blockOperation in a SDK. The SDK is initialised as singleton