ubicación ubicacion servicios segundo puedo por plano localizacion exacta activar ios objective-c cllocationmanager

servicios - ubicacion segundo plano iphone



Comprobación del permiso de servicio de ubicación en iOS (7)

Solución Swift 3.0 y iOS 10:

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 } }

¿Cómo puedo verificar si el servicio de ubicación está habilitado para mi aplicación?

Tengo 2 guiones gráficos y quiero verificar el servicio de ubicación. Si el servicio de ubicación está habilitado para mi aplicación, deseo iniciar el guión gráfico del mapa con la ubicación. De lo contrario, quiero iniciar otro guión gráfico. ¿Cómo puedo hacer programáticamente?


Después de mucha investigación. Yo recomendaría mostrar este mensaje en una etiqueta y no en una vista de alerta. porque hay muchos casos para probar en contra (el usuario deshabilita el servicio de ubicación en general o solo para la aplicación, eliminar la aplicación, reinstalar).

Uno de estos casos hace que su alerta muestre su mensaje junto con el mensaje de alerta de Apple al mismo tiempo. tu alerta estará detrás de la alerta de Apple. que es un comportamiento confuso y no lógico.

Recomiendo lo siguiente:

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''s 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 } }

C objetivo:

- (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''s 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; } }


Este es el correcto.

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]; } }


La mejor manera, manejando todos los casos! ->

//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 }


Verifique la propiedad locationServicesEnabled de CLLocationManager para verificar la disponibilidad de todo el sistema. Use el método locationManager: didFailWithError: de CLLocationManagerDelegate y busque un error kCLErrorDenied para ver si el usuario denegó servicios de ubicación.

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]; }

para su aplicación use este código

- (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''s a relatively recent event, turn off updates to save power } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"%@",error); }

si el servicio de localización se deshabilita para su aplicación, entonces le da error

Error Domain=kCLErrorDomain Code=1 "The operation couldn’t be completed. (kCLErrorDomain error 1.)"


Probado en iOS 9.2

Para obtener actualizaciones de ubicación siempre debemos verificar

  • Servicios de ubicación habilitados en el dispositivo iOS del usuario y
  • Servicios de ubicación habilitados para aplicaciones particulares

y ejecutando al usuario en la pantalla de configuración correcta para habilitar

Lanzar la página de configuración de ubicación del dispositivo iOS

Paso.1 Vaya a Configuración del proyecto -> Información -> Tipos de URL -> Agregar nuevos esquemas de URL

Paso.2 Use el código a continuación para abrir la página de configuración de ubicación del teléfono directo: (Nota: El esquema de URL es diferente en iOS 10+, verificamos la versión como se indica 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]];

Lanzar la página de configuración de ubicación de la aplicación

Use el código siguiente para abrir la página de configuración de ubicación de la aplicación directa

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

Aquí está el ejemplo completo del código:

#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''s start location updates [locationManager startUpdatingLocation]; } }

Gestione la respuesta del usuario y haga clic en Configuración de ubicación correcta

-(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 } }


-(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]; } } }

Motivo detrás de esto, este método llamará cuando su servicio desactive el servicio de ubicación. este código es útil para mí