Verify location service resolution on iOS

How to check if location service is enabled for my application?

I have 2 storyboards and I want to check the location service. If the location service is enabled for my application, I want to run a storyboard map with a location. Otherwise, I want to start another storyboard. How can I do it programmatically?

+42
ios objective-c cllocationmanager
Mar 01 '13 at 7:59
source share
7 answers

It is right.

if ([CLLocationManager locationServicesEnabled]){ NSLog(@"Location Services Enabled"); if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){ alert = [[UIAlertView alloc] initWithTitle:@"App Permission Denied" message:@"To re-enable, please go to Settings and turn on Location Service for this app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } } 
+125
Mar 01 '13 at 8:40
source share

Tested on iOS 9.2

To get location updates, we should always check

  • Location services are enabled on the user's iOS device and
  • Application-specific location properties

and launching the user on the correct settings screen to enable

Launch iOS device location settings page

Step .1 Go to project settings → Information → URL types → Add new URL schemes

enter image description here

Step 2. Use the code below to launch the direct phone settings page: (Note: URL scheme is different in iOS 10+, we check the version as indicated here )

  #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending) //Usage NSString* url = SYSTEM_VERSION_LESS_THAN(@"10.0") ? @"prefs:root=LOCATION_SERVICES" : @"App-Prefs:root=Privacy&path=LOCATION"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]]; 

enter image description here

Launch the application location settings page

Use the code below to launch the direct application location settings page

 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; 

enter image description here

Here is an example of the complete code: #define SYSTEM_VERSION_LESS_THAN (v) ([[[[UIDevice currentDevice] systemVersion] compare: v options: NSNumericSearch] == NSOrderedAscending)

 CLLocationManager *locationManager; -(void) checkLocationServicesAndStartUpdates { locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [locationManager requestWhenInUseAuthorization]; } //Checking authorization status if (![CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!" message:@"Please enable Location Based Services for better results! We promise to keep your location private" delegate:self cancelButtonTitle:@"Settings" otherButtonTitles:@"Cancel", nil]; //TODO if user has not given permission to device if (![CLLocationManager locationServicesEnabled]) { alertView.tag = 100; } //TODO if user has not given permission to particular app else { alertView.tag = 200; } [alertView show]; return; } else { //Location Services Enabled, let start location updates [locationManager startUpdatingLocation]; } } 

Contact the customer responsible for the request and run the correct location settings.

 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if(buttonIndex == 0)//Settings button pressed { if (alertView.tag == 100) { //This will open ios devices location settings NSString* url = SYSTEM_VERSION_LESS_THAN(@"10.0") ? @"prefs:root=LOCATION_SERVICES" : @"App-Prefs:root=Privacy&path=LOCATION"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]]; } else if (alertView.tag == 200) { //This will opne particular app location settings [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; } } else if(buttonIndex == 1)//Cancel button pressed. { //TODO for cancel } } 
+24
Mar 14 '16 at 8:42 on
source share
 -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ NSLog(@"%@",error.userInfo); if([CLLocationManager locationServicesEnabled]){ NSLog(@"Location Services Enabled"); if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"App Permission Denied" message:@"To re-enable, please go to Settings and turn on Location Service for this app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } } } 

The reason for this is that this method will call when your service disables the location service. This code is useful to me.

+20
Jan 15 '14 at 4:42
source share

Check the CLLocationManager property locationServicesEnabled to verify system availability. Use the CLLocationManagerDelegate locationManager: didFailWithError: method and check for a kCLErrorDenied error to see if the user has refused location services.

 BOOL locationAllowed = [CLLocationManager locationServicesEnabled]; if (!locationAllowed) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service Disabled" message:@"To re-enable, please go to Settings and turn on Location Service for this app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } 

for your application use this code

 - (void)viewDidLoad { locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyKilometer; // Set a movement threshold for new events. locationManager.distanceFilter = 500; [locationManager startUpdatingLocation]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { // If it a relatively recent event, turn off updates to save power } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"%@",error); } 

if the location service is disabled for your application, then it will give you an error

 Error Domain=kCLErrorDomain Code=1 "The operation couldn't be completed. (kCLErrorDomain error 1.)" 
+11
Mar 01 '13 at 8:01
source share

After a big investigation. I would recommend displaying this message on a label, rather than on a warning screen. because there are many cases to test (the user disables the location service in general, or just the application for the application, reinstalls).

One of these cases causes your alert to simultaneously display your message along with the Apple alert message. your warning will be behind the apple warning. which is confusing and illogical behavior.

I recommend the following:

Swift 3:

 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .notDetermined: Log.verbose("User still thinking granting location access!") manager.startUpdatingLocation() // this will access location automatically if user granted access manually. and will not show apple request alert twice. (Tested) break case .denied: Log.verbose("User denied location access request!!") // show text on label label.text = "To re-enable, please go to Settings and turn on Location Service for this app." manager.stopUpdatingLocation() loadingView.stopLoading() break case .authorizedWhenInUse: // clear text label.text = "" manager.startUpdatingLocation() //Will update location immediately break case .authorizedAlways: // clear text label.text = "" manager.startUpdatingLocation() //Will update location immediately break default: break } } 

Objective-C:

 - (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { switch (status) { case kCLAuthorizationStatusNotDetermined: { DDLogVerbose(@"User still thinking granting location access!"); [locationManager startUpdatingLocation]; // this will access location automatically if user granted access manually. and will not show apple request alert twice. (Tested) } break; case kCLAuthorizationStatusDenied: { DDLogVerbose(@"User denied location access request!!"); // show text on label label.text = @"To re-enable, please go to Settings and turn on Location Service for this app."; [locationManager stopUpdatingLocation]; [loadingView stopLoading]; } break; case kCLAuthorizationStatusAuthorizedWhenInUse: case kCLAuthorizationStatusAuthorizedAlways: { // clear text label.text = @""; [locationManager startUpdatingLocation]; //Will update location immediately } break; default: break; } } 
+10
Sep 14 '15 at 8:50
source share



Swift 3.0 and iOS 10 solution:




 self.locationManager?.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.denied { locationManager?.delegate = self locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation locationManager?.distanceFilter = distanceFiler locationManager?.startUpdatingLocation() }else{ let alertView = UIAlertView(title: "Location Services Disabled!", message: "Please enable Location Based Services for better results! We promise to keep your location private", delegate: self, cancelButtonTitle: "Settings", otherButtonTitles: "Cancel") alertView.delegate = self alertView.show() return } @objc(alertView:clickedButtonAtIndex:) func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { if buttonIndex == 0 { if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") { UIApplication.shared.open(url, completionHandler: .none) } } else if buttonIndex == 1 { //TODO for cancel } } 
+2
Apr 21 '17 at 9:16 on
source share

The best way to get things done! →

 //First, checking if the location services are enabled if(![CLLocationManager locationServicesEnabled]){ [self showMessage:@"Please enable location services to detect location!" withTitle:@"Location not enabled"]; } else if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){ //Now if the location is denied. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Enable location permission" message:@"To auto detect location, please enable location services for this app" preferredStyle:UIAlertControllerStyleAlert]; alertController.view.tintColor = AppColor; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Cancel action"); }]; UIAlertAction *goToSettings = [UIAlertAction actionWithTitle:@"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { //Simple way to open settings module NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; [[UIApplication sharedApplication] openURL:url]; }]; [alertController addAction:cancelAction]; [alertController addAction:goToSettings]; [self presentViewController:alertController animated:YES completion:^{ alertController.view.tintColor = AppColor; }]; } else{ //Do whatever you want here } 
+1
Apr 05 '17 at 6:31 on
source share



All Articles