ios - 如何在后台连续播放闹钟声音

标签 ios iphone uilocalnotification

我正在开发一个应用程序,我想在其中播放闹钟。一旦我收到本地通知,闹钟就会在后台响起,并在我按下按钮时停止。

这是我的代码

NSDate *pickerDate = [self.timePicker date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
    fromDate:pickerDate];

NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
    fromDate:pickerDate];

NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setHour:[timeComponents hour]];
NSLog(@"set hour component %ld",(long)[timeComponents hour]); // Notification will fire in one minute

[dateComps setMinute:[timeComponents minute]];
NSLog(@"set setMinute component %ld",(long)[timeComponents minute]);
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];

UILocalNotification *localNotification = [[UILocalNotification alloc] init]; //Create the localNotification object
[localNotification setFireDate:itemDate]; 
//Set the date when the alert will be launched using the date adding the time the user selected on the timer

[localNotification setAlertAction:@"Open"]; //The button's text that launches the application and is shown in the alert
[localNotification setAlertBody:@"Wake up"]; //Set the message in the notification from the textField's text
localNotification.soundName = UILocalNotificationDefaultSoundName;
[localNotification setHasAction: YES]; //Set that pushing the button will launch the application
[localNotification setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber]+1];
//Set the Application Icon Badge Number of the application's icon to the current Application Icon Badge Number plus 1
[localNotification setUserInfo:[NSDictionary dictionaryWithObject:@"Alarm1" forKey:@"uid"]];
if (isRepeat) {
    localNotification.repeatInterval = NSDayCalendarUnit;
}

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
//Schedule the notification with the system

使用上面的代码,声音只播放 30 秒。我想让它连续播放。我搜索了很多但找不到。

谢谢

最佳答案

这是做不到的,我这么说的意思是当应用程序处于后台时,你不能像你在收到通知时所说的那样在后台播放声音。苹果推送和本地通知都不支持,只能添加提示音,不会一直播放。

如果你想在后台播放声音,只有当声音开始在前台播放而不是你在后台播放时才能完成,因为它只会使用 AVAudioPlayer Session PlayBack 在后台继续播放。

如果你认为你可以添加定时器,但定时器在后台也不起作用。

关于ios - 如何在后台连续播放闹钟声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20835247/

相关文章:

ios - 取消 UILocalNotification

iOS UILocalNotification 仅在应用程序未运行时发出声音(无警报)

ios - iOS 中的奇怪崩溃

iOS 7 导航栏隐藏内容

ios - 减少在 iOS 上使用 OpenCv 的方法消耗的内存

ios - 从日期选择器获取日期到变量中的字符串

iphone - iOS:如何链接正在开发的App Store链接

iphone - 即使使用正确的分发配置文件,为 iCloud 选择 "Enable Entitlements"也会导致协同设计错误

ios - iOS 11 的 Storyboard尺寸?

ios - iOS本地通知