【发布时间】:2015-01-12 22:39:27
【问题描述】:
因为UILocalNotification 在应用程序处于活动状态时没有显示,我正在尝试配置一个UIAlertController 并在它出现时播放一点声音。
我没有问题,在AppDelegate,处理通知/创建警报。我的问题与声音有关。确实,它播放不正确。
这是我目前所拥有的:
//...
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Notifications permissions
let types: UIUserNotificationType = UIUserNotificationType.Sound | UIUserNotificationType.Alert
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
return true
}
func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!) {
let state : UIApplicationState = application.applicationState
var audioPlayer = AVAudioPlayer()
if (state == UIApplicationState.Active) {
// Create sound
var error:NSError?
var audioPlayer = AVAudioPlayer()
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
let soundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "wav")!)
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
if (error != nil) {
println("There was an error: \(error)")
} else {
audioPlayer.prepareToPlay()
audioPlayer.play()
}
// Create alert
let alertController = UIAlertController(title: "Alert title", message: "Alert message.", preferredStyle: .Alert)
let noAction = UIAlertAction(title: "No", style: .Cancel) { (action) in
// ...
}
let yesAction = UIAlertAction(title: "Yes", style: .Default) { (action) in
// ...
}
alertController.addAction(noAction)
alertController.addAction(yesAction)
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
这样,当玩家通过这条线时:audioPlayer.play()
它只播放不到一秒钟。就像它突然被释放一样(?)。
我尝试了以下两件事:
- 将
AVAudioPlayer状态切换回非活动状态:AVAudioSession.sharedInstance().setActive(false, error: nil)在警报创建之前(或在显示之后)。如果我这样做,声音就会正确播放。但是,这种方法是同步(阻塞)操作,所以它会延迟其他事情(在声音之后显示警报)。显然不是一个好的解决方案。 - 将 audioPlayer 属性 (
var audioPlayer = AVAudioPlayer()) 移动到类级别,就在窗口 (var window: UIWindow?) 下方。如果我这样做,声音就会正确播放,并且警报也会正确显示。
我不明白为什么会这样。我错过了什么吗?这是解决我的问题的正确方法吗?
提前感谢所有可以帮助我理解/解决此问题的人。
【问题讨论】:
标签: swift avaudioplayer uilocalnotification appdelegate uialertcontroller