Si la aplicación se está ejecutando y la clase CLLocationManagerDelegate es el primer plano (es decir, visible), entonces didEnterRegions se activa y obtengo tanto el NSLog como el AlertView. Sin embargo, no obtengo nada cuando la aplicación está en segundo plano o, esencialmente, si la pantalla muestra algo más que la clase de delegado.didEnterRegion funciona en primer plano pero no en fondo u otros VCs
He configurado "Registros de aplicación para actualizaciones de ubicación" en "Modos de fondo requeridos" en la lista, aunque no estoy seguro de que sea necesario.
Esto es lo que creo que es el código relevante, aunque puedo estar equivocado (y con mucho gusto añadiré más). Debo señalar que todo en viewDidLoad está envuelto en un if que comprueba si la monitorización de región está disponible y habilitada.
- (void)viewDidLoad
{
NSLog(@"MapViewController - viewDidLoad");
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
self.locationManager.delegate = self;
[self.locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
NSLog(@"MapViewController - didEnterRegion");
NSLog(@"MVC - didEnterRegion - region.radius = %f", region.radius);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"entered region..." message:@"You have Entered the Location." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
alert.tag = 2;
[alert show];
}
aquí es donde consigo la lista de regiones está supervisando, en AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// other code
NSLog(@"LISTING ALL REGIONS MONITORED");
NSArray *regions = [self.locationManager.monitoredRegions allObjects];
if (!regions) {
NSLog(@"no regions found");
} else {
NSLog(@"got %d monitored regions", [regions count]);
for (int i = 0; i < [regions count]; i++) {
CLRegion *region = [regions objectAtIndex:i];
NSLog(@"region %d's identifier = %@", i, region.identifier);
NSLog(@"region: radius: %@", region.radius);
}
}
// other code
}
me llaman startMonitoringForRegion dos veces, aquí es el lugar principal:
- (void)doneButtonTapped {
NSLog(@"doneButtonTapped");
if (self.locationIdentifier) {
if ([CLLocationManager regionMonitoringEnabled] && [CLLocationManager regionMonitoringAvailable]) {
// core data setup
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"LocationReminder" inManagedObjectContext:self.managedObjectContext];
fetchRequest.entity = entityDescription;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"locationIdentifier == %@", self.locationIdentifier];
fetchRequest.predicate = predicate;
NSError *error;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (results) {
// get the LocationReminder
LocationReminder *retrievedReminder = [results objectAtIndex:0];
retrievedReminder.audioURI = [[[self.audioPlayers objectAtIndex:self.selectedCell] url] absoluteString];
retrievedReminder.userRecording = nil;
// start monitoring it's region
NSArray *coordinateArray = [retrievedReminder.locationIdentifier componentsSeparatedByString:@", "];
CLLocationCoordinate2D coordinate = {[[coordinateArray objectAtIndex:0] doubleValue], [[coordinateArray objectAtIndex:1] doubleValue]};
CLRegion *newRegion = [[CLRegion alloc] initCircularRegionWithCenter:coordinate radius:250.0 identifier:retrievedReminder.locationIdentifier];
NSLog(@"about to monitor region with radius: %f", newRegion.radius);
[self.locationManager startMonitoringForRegion:newRegion desiredAccuracy:kCLLocationAccuracyBest];
// save the LocationReminder
if (![self.managedObjectContext save:&error]) {
NSLog(@"hmm. no managed object context. must be something space-time going on");
} else {
NSLog(@"saved locationReminder, locationIdentifier = %@", retrievedReminder.locationIdentifier);
}
} else {
NSLog(@"ERROR: no LocationReminder retreived for predicate: %@", predicate);
}
}
// get the mapview controller off of the navigation stack
for (UIViewController *viewController in self.navigationController.viewControllers) {
if ([viewController isKindOfClass:[MapViewController class]]) {
MapViewController *mapVC = (MapViewController *)viewController;
mapVC.audioURI = [[[self.audioPlayers objectAtIndex:self.selectedCell] url] absoluteString];
[self.navigationController popToViewController:mapVC animated:YES];
}
}
}
Y porque Tengo la sensación de que podría ser importante, aquí está el getter para locationManager:
- (CLLocationManager *)locationManager {
NSLog(@"MapViewController - locationManager");
if (_locationManager) {
return _locationManager;
} else {
_locationManager = [[CLLocationManager alloc] init];
return _locationManager;
}
}
ACTUALIZACIÓN 1: A través de los foros de Apple (donde hice una cruz) alguien mencionó que AlertView solo se mostrará en primer plano. Aún así, el NSLog tampoco se dispara. Supongo que debería funcionar.
¿Se puede incluir el código al que se llama el startMonitoringForRegion? El código incluido en este momento no lo muestra y solo activaría los métodos de devolución de llamada relacionados con cambios de ubicación significativos. Y esos eventos no se dispararán desde el simulador en mi experiencia. –