ios - 前台本地通知

标签 ios objective-c notifications local

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

    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

当我记录通知的声音文件等属性时..它们工作正常...但没有声音...

最佳答案

在前台,您必须提供警报 View 并在需要时播放声音,通知只会调用 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];

关于ios - 前台本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17044373/

相关文章:

iphone - 单例类内存泄漏

ios - 如何将 Storyboard连接到代码

objective-c - 确定 NSString 中的路径是指向目录还是​​文件?

Flutter snackbar 替代方案还是比将所有内容包装在 Scaffold 中更简单的方法?

ios - 在 Firebase iOS 中重用凭据以通过 Apple 登录

iphone - 我怎样才能避免来自 AlassetLibrary 的位置服务?

objective-c - 方法: multiple parameters or structure?

iphone - 为 iphone 编写 API 时错误处理的最佳做法是什么?

Android 8.0 双重通知音效

iphone - 为通知代理注销设备