2014-07-15 49 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

相關問題