iOs 8,在后台开始播放声音,闹钟应用程序

iOs 8,在后台开始播放声音,闹钟应用程序,ios,audio,swift,alarm,Ios,Audio,Swift,Alarm,我知道在软件方面有很多问题,但这是“最新”的一个。问题是,我正在尝试创建一个报警应用程序,我知道有一些报警应用程序可以完美地工作(不知何故),即使应用程序没有运行并且在后台 我的问题是:在你的应用程序已经在后台之后,你如何开始播放声音 UILocalNotification非常好,但是只有在用户单击了您的通知之后,您才能获得应用程序:(\uuIdReceiveLocalNotification:),因此使用AVAudioPlayer播放声音不起作用,我想播放声音,不管用户是否单击它。当然,使用所

我知道在软件方面有很多问题,但这是“最新”的一个。问题是,我正在尝试创建一个报警应用程序,我知道有一些报警应用程序可以完美地工作(不知何故),即使应用程序没有运行并且在后台

我的问题是:在你的应用程序已经在后台之后,你如何开始播放声音

UILocalNotification非常好,但是只有在用户单击了您的通知之后,您才能获得
应用程序:(\uuIdReceiveLocalNotification:)
,因此使用AVAudioPlayer播放声音不起作用,我想播放声音,不管用户是否单击它。当然,使用
所需的背景模式:应用程序在
info.plist
中使用AirPlay播放音频或流式播放音频/视频。一旦音乐开始播放,即使我转到背景,它也会继续播放

我不想使用UILocalNotification声音,因为它被限制在30秒之内,并且只能播放与应用程序捆绑在一起的声音

有什么见解吗?想法

示例代码:

    var notif = UILocalNotification()
    notif.fireDate = self.datePicker.date
    notif.alertBody = "test"
    UIApplication.sharedApplication().scheduleLocalNotification(notif)
当用户选择和报警并单击保存时,将调用上述代码

下面是AppDelegate中发生的事情:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    NSLog("launched")
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
        UIUserNotificationType.Badge, categories: nil
        ))
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    self.sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "caf"))
    self.audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)

    return true
}

func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!){
    audioPlayer.play()
    NSLog("received local notif")


}

您需要保留对
AVAudioPlayer
btw的强引用,这样它就不会发布,
audioplayer.play()
不会做任何事情…

最后,我设法用NSTimer做到了这一点

func applicationWillResignActive(application: UIApplication) {
    var timer = NSTimer(fireDate: NSDate(timeIntervalSinceNow: 20), interval: 60.0, target: self, selector: Selector("playAlarm"), userInfo: nil, repeats: false)
    NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}
func playAlarm() {
    self.sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "caf"))
    self.audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
    audioPlayer.play()
}
在其他地方,UILocalNotification与此计时器同步,以获得良好的用户体验


虽然我不确定这是否会通过苹果,但我看不出有任何理由不这样做:\

如果你的应用程序在后台,那么在通知触发后应该调用
didreceivelocalnotification
。也许你可以把你的代码放在那里播放声音。我试过很多次了,没有,只有在用户实际点击通知后才会被触发。我还是会编辑我的问题。所以,当应用程序在后台时,你们可以通过这个代码开始播放声音吗?是的,你们可以,试试看,它对我有用。。。还没有将应用发布到商店,想知道是否有人能证实这一点。我不明白为什么它能工作。如果应用程序在后台运行,它通常会在几分钟后挂起。因此,如果应用程序处于挂起状态,计时器将不会触发playAlarm()。嘿,朋友,你的闹钟有github repo吗?谢谢这项技术奏效了。你能在app store中发布你的应用吗