Swift如何在不继承AVAudioPlayer的类上使用AVAudioPlayerDelegate?

时间:2017-09-25 09:40:49

标签: swift xcode delegates avaudioplayer

class myClass: AVAudioPlayerDelegate{
    var player = AVAudioPlayer()

    init(){
        player.delegate = self
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
          print("The song ended")
    }
}

我正在学习Swift并尝试制作音乐播放应用。我有自定义类,其AVAudioPlayer对象名为播放器作为其属性。如何将AVAudioPlayerDelegate方法与播放器对象一起使用?

当得到这样的代码时,我得到错误:

  

myClass类型不符合协议NSObjectProtocol

1 个答案:

答案 0 :(得分:2)

继承自NSObject。

class myClass: NSObject, AVAudioPlayerDelegate {
    var player = AVAudioPlayer()

    init(){
        player.delegate = self
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
          print("The song ended")
    }
}