0

这个问题一直让我发疯。我想要做的是在用户进入某个区域时触发通知。但是,我想要的是,如果用户正在使用该应用程序显示一条警报消息,并且如果该应用程序在后台显示一个本地通知。

这是我的代码:

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
    UIApplication *app = [UIApplication sharedApplication];

    if (app.applicationState == UIApplicationStateActive)
    {
        NSURL *musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"]];
        AVAudioPlayer *audioFile = [[AVAudioPlayer alloc] init];
        audioFile = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:NULL];
        [audioFile play];

        UIAlertView *arrivingDestinationAlert = [[UIAlertView alloc] initWithTitle: @"Arriving" message:[NSString stringWithFormat:@"Alert"]  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [arrivingDestinationAlert show];
    }else if(app.applicationState == UIApplicationStateBackground || app.applicationState == UIApplicationStateInactive)
    {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.alertBody = [NSString stringWithFormat:@"%d to reach your destination", self.distToRemind];
        notification.alertAction = @"Destination Approaching";
        notification.hasAction = YES;
        notification.soundName = UILocalNotificationDefaultSoundName;
        [app presentLocalNotificationNow:notification];
    }

    [manager stopMonitoringForRegion:region];
}

我之前做的是工作。这是午餐本地通知,而不询问应用程序的状态是后台还是活动。我只是在didEnterRegion触发时立即通知通知。但是现在我可以让它工作了。

我错过了什么吗?

4

1 回答 1

0

I think you are checking for the active state in the wrong spot. I do something very similar, but I check for active state in the AppDelegate when the notification fires. You should intercept the local notification in -didReceiveLocalNotification. If the state is active, push your UIAlertView there. If you fire the alert from the -didEnterRegion or -didExitRegion from the background, it will never be seen.

于 2012-10-10T00:15:59.717 回答