我知道 SOF 上有很多问题,但这是“最新”的一个。事实上,我正在尝试创建一个闹钟应用程序,并且我知道已经有一些完美运行的闹钟应用(不知何故),即使该应用程序未运行且在后台中。
我的问题是:如何在您的应用程序已经在后台运行之后开始播放声音?
UILocalNotification 很棒,但只有在用户已经单击通知后才会得到 application:(_:didReceiveLocalNotification:)
,因此使用 AVAudioPlayer 播放声音没有用,我想无论用户是否单击它都要播放声音。当然,在 info.plist
中设置了 Required background modes: App plays audio or streams audio/video using AirPlay
。一旦开始播放音乐,即使我进入后台,它仍将继续播放。
我不想使用 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
的强引用,这样它就不会被释放了,audioplayer.play()
才会起作用...