Swift 2.0在后台模式下在app delegate中播放自定义声音

时间:2015-11-16 10:57:10

标签: ios avaudioplayer

我正在使用Google Cloud消息将通知推送到我用Swift 2.0 xCode 7.1编写的iOS应用程序。 GCM不允许自定义通知声音。 见这里:https://developers.google.com/cloud-messaging/http-server-ref

所以我关闭了默认声音,并且每当调用'didReceiveRemoteNotification'时我都会尝试播放声音。我的问题是在后台模式下声音没有播放。但是如果我把代码(下面)放在'didFinishLaunchingWithOptions'中它完美地工作,就在我想要它播放时。 我在info.plist中添加了更多背景信息。就像我说的那样,当推送通知到来时它才起作用。

    let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("GMNotification", ofType: "wav")!)
    print(alertSound)

    //var error:NSError?
    do {
        try self.audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, fileTypeHint:nil)
        self.audioPlayer.prepareToPlay()
        self.audioPlayer.play()
        print("PLAY !!!")
    } catch {
        print("Error ???")
    }

enter image description here

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您必须创建一个共享实例" Singelton"播放声音。请参阅:

Swift - AVAudioPlayer, sound doesn't play correctly

这应该告诉你如何做到

相关问题