在iOS中构建警报应用程序

问题描述 投票:-1回答:2

我想在iOS中开发一个警报应用程序。到目前为止,我已经创建了基本用户界面,用户可以选择触发警报的时间。代码使用以下代码计划此时的一个本地通知:

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分钟,则音乐不会播放。

我有以下问题:

  1. 在“x”分钟的时间间隔之后运行特定任务的方法/黑客是什么?
  2. 在iOS中实现闹钟的最佳方法是什么?

我将不胜感激任何关于这个主题的建议和想法。

编辑:我在App Store上发现了一个alarm application,可以在触发警报时播放无限时间的闹钟音乐。这个应用程序如何确定何时启动闹钟音乐?

ios objective-c nsnotificationcenter taskscheduler
2个回答
1
投票

您应该通过将sound属性设置为content来指定音乐名称。 所以代替: content.sound = [UNNotificationSound defaultSound];

你应该设置: content.sound = [UNNotificationSound soundNamed:@"yourSoundName.mp3"];

另外,请确保您的音乐长度不超过30秒。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.