2014-07-15 53 views
13

我知道SOF有很多问题,但这是“最新”的一个。事情是,我正在尝试创建和报警应用程序,而且我知道有一个事实,即有应用程序没有运行并且位于后台的警报应用程序完美工作(以某种方式)。iOs 8,在后台开始播放声音,闹钟应用程序

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

UILocalNotification非常好,但用户已经点击了通知后才会得到application:(_:didReceiveLocalNotification:),所以使用AVAudioPlayer播放声音无法正常工作,我想播放声音,无论用户点击它还是不用,吨。当然Required background modes: App plays audio or streams audio/video using AirPlay已在info.plist中设置。一旦音乐开始播放,即使我进入背景,它也会继续播放。

我不想使用UILocalNotificaation声音因为它限制在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()不会做什么...

+0

如果您的应用程序在后台,'didreceivelocalnotification'应后,被称为通知被解雇。也许你可以把你的代码放在那里播放声音。 – Chris

+0

我尝试过很多次了,它不会,只有在用户实际点击通知后才会被触发。无论如何,我会编辑我的问题。 – Nour1991

回答

9

最后,我设法用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与此计时器同步,以获得良好的用户体验。

虽然我不知道这是否会经过苹果,但我看不出有任何理由为什么它不会:\

+0

那么,您可以通过此代码开始播放声音,当应用程序在后台? – somedev

+0

是的,你可以,试试看,它适用于我......没有发布应用程序存储,但很想知道,如果有人可以证实这一点.. – Nour1991

+7

我不明白为什么它的作品。如果应用程序在后台运行,它通常会在几分钟后暂停。所以,如果app处于挂起状态,定时器不会触发playAlarm()。 – somedev

相关问题