在iOS中构建报警应用程序

hwamh0ep  于 2023-05-23  发布在  iOS
关注(0)|答案(2)|浏览(129)

我想在iOS中开发一个闹钟应用程序。到目前为止,我已经创建了基本的UI,用户可以在其中选择警报应该触发的时间。代码使用以下代码为该时间安排一个本地通知:

UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    content.title = @"Helloooooo...";
    content.body = @"Time to wake up!";
    content.sound = [UNNotificationSound defaultSound];
    
    //create trigger
    UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];
    
    NSString *identifier = @"test";
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
                                                                          content:content trigger:trigger];
    
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Something went wrong: %@",error);
        }
    }];

现在,当触发此通知时,我想播放音乐(如闹钟铃声)。经过大量的研究,我明白了,当应用程序在后台时,没有通知触发事件的回调。
我尝试的另一种方法是,代码尝试在某个计时器之后调用playAlarmTone方法:

UIApplication *app = [UIApplication sharedApplication];
    
    //create new uiBackgroundTask
    __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
    //and create new timer with async call:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //run function methodRunAfterBackground
        NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:lroundf(secondsBetween)
                                         target:self
                                       selector:@selector(playAlarmTone)
                                       userInfo:nil
                                        repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });

但是使用这种方法,如果闹钟设置为距离当前时间超过15分钟,则音乐不会播放。
什么是一个方法来运行特定的任务后的时间间隔为“x”分钟?
我在App Store上发现了一款alarm application,它可以在触发闹钟时无限时间播放闹钟音乐。这个应用程序如何确定何时启动闹钟音乐?

bmvo0sr5

bmvo0sr51#

您应该通过将sound属性设置为content来指定音乐名称。
因此,而不是:
content.sound = [UNNotificationSound defaultSound];
您应该设置:
content.sound = [UNNotificationSound soundNamed:@"yourSoundName.mp3"];
此外,请确保您的音乐长度不超过30秒。

uwopmtnx

uwopmtnx2#

您是否已经考虑过使用NSTimer scheduledtimerwithtimeinterval?这可以用于根据您的需要在一段时间间隔后执行操作。此外,请查看Andrew的这篇文章http://andrewmarinov.com/building-an-alarm-app-on-ios/

相关问题