我想在中开发一个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分钟,音乐就不会播放。
我有以下问题:
我希望就这一议题提出任何建议和想法。
编辑:我在App上找到了一个报警应用,当触发警报时,它可以播放无限时间的警报音乐。这个应用程序如何确定何时启动警报音乐?
发布于 2019-03-20 12:58:02
应该通过将sound属性设置为content来指定音乐名称。
因此,与其:
content.sound = [UNNotificationSound defaultSound];
你应该设置:
content.sound = [UNNotificationSound soundNamed:@"yourSoundName.mp3"];
此外,请确保您的音乐长度不超过30秒。
发布于 2019-03-25 14:20:43
您考虑过在时间间隔内使用NSTimer scheduledtimerwithtimeinterval吗?这可以用于根据需要在一段时间间隔后执行操作。另外,请查看本文中的http://andrewmarinov.com/building-an-alarm-app-on-ios/。
https://stackoverflow.com/questions/55259375
复制相似问题