因为在应用程序处于活动状态时没有显示UILocalNotification,所以我正在尝试配置UIAlertController并在它出现时播放一些声音.
原文链接:https://www.f2er.com/swift/320132.html我在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?).如果我这样做,声音播放正确,警报也正确显示.
我不明白为什么它会这样.我错过了什么吗?这是解决我问题的正确方法吗?
提前感谢所有能帮助我理解/解决这个问题的人.