如何在后台连续播放闹铃声

时间:2013-12-30 07:29:34

标签: 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秒。我希望它能够持续发挥。我搜索了很多但找不到。

由于

1 个答案:

答案 0 :(得分:3)

这是不可能的,说这是我的意思是你不能在后台播放声音,就像你在接收通知时说的那样。 Apple推送和本地通知都不支持此功能,您只能添加通知声音,但不会连续播放。

如果你想在后台播放声音,只有当声音在前景中开始播放而不是在背景中播放时,才能使用AVAudioPlayer Session PlayBack继续在后台播放。

如果您认为可以添加计时器,但计时器也不能在后台运行。