前台本地通知

5

当报警时,通知在后台工作正常,如下所示:

    UILocalNotification *notification1=[[UILocalNotification alloc]init];
    notification1.fireDate=alramtime;
    notification1.alertBody=@"Training Time";
    notification1.repeatInterval=NSDayCalendarUnit;

    notification1.soundName=@"Alarm.caf";

    ///////
    previousnotif=[[NSUserDefaults standardUserDefaults]objectForKey:@"notif1"];
    previous=[NSKeyedUnarchiver unarchiveObjectWithData:previousnotif];

    NSLog(@"alarm %@",previous);
    if (previous!= NULL) {
        [[UIApplication sharedApplication]cancelLocalNotification:previous];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"notif1"];

    }
    NSData *alarm1=[NSKeyedArchiver archivedDataWithRootObject:notification1];
    [notifdefaults setObject:alarm1 forKey:@"notif1"];
    /////////


    [[UIApplication sharedApplication] scheduleLocalNotification:notification1];
    NSLog(@"new alarm %@",notification1);

但是,当我将它修改为可以在前台播放时,如下所示:...它不起作用...只有警报出现,没有声音?
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{

UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {


   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"KNIP"
                                                   message:notification.alertBody
                                                   delegate:self cancelButtonTitle:@"Close"
                                          otherButtonTitles:nil];  

[alert show];

}
@end

当我查看通知的声音文件等属性时,它们都正常工作,但是没有声音...

2个回答

8

在前台,如果需要,您需要提供警报视图并播放声音,通知将仅调用 applicationDidReceiveLocalNotification。您可以使用 AVAudioPlayer 播放声音。

 //Playing sound
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath],notification.soundName]];

        AVAudioPlayer *newAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        self.audioPlayer = newAudioPlayer;
        self.audioPlayer.numberOfLoops = -1;
        [self.audioPlayer play];
        [newAudioPlayer release];

7
如果应用程序在系统发送通知时处于前台并可见,则不会显示警报,不会标记图标,也不会播放声音。但是,如果应用程序委托实现了它,则会调用application:didReceiveLocalNotification:方法。此方法接收UILocalNotification实例,并且委托可以检查其属性或访问userInfo字典中的任何自定义数据。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接