问题
I am using startMonitoringForRegion
to monitor specific region.
When App is not running I have successfully generated a local notification when a user enters/leaves a particular location by comparing [launchOptions objectForKey:@"UIApplicationLaunchOptionsLocationKey"]
in AppDelegate.
But now I am not able to understand how can I know that a user enters in a location or leaves a location. I am not able to find a way to check the response. Can I show the response in the alert body? I searched in internet but unable to find any tutorial that have written some code in AppDelegate.
回答1:
you can use location manager delegate method
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region{
if (state == CLRegionStateInside) {
// We entered a region
NSLog(@"Inside region");
if([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground){
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"Region Detected";
notification.soundName = @"Default";
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
} else if (state == CLRegionStateOutside) {
// We are outside region
NSLog(@"Outside region");
}
}
IN APPDELEGATE
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"PerformAction" object:nil userInfo:nil];
}
IN your ViewController viewDidLoad Method :
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performAction) name:@"PerformAction" object:nil];
In your same viewController add the following method and perform ur action
-(void)performAction
{
// perform your action
}
来源:https://stackoverflow.com/questions/28831572/startmonitoringforregion-when-app-close