Search code examples
swiftxcodedelegatesavaudioplayer

Swift How can I use AVAudioPlayerDelegate on a class that doesn't inherit AVAudioPlayer?


class myClass: AVAudioPlayerDelegate{
    var player = AVAudioPlayer()

    init(){
        player.delegate = self
    }

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

I am learning Swift and trying to make a music playing app. I have custom class that has AVAudioPlayer object called player as its property. How can I use the AVAudioPlayerDelegate methods with the player object?

When having the code like this I get the error:

The type myClass does not conform to the protocol NSObjectProtocol


Solution

  • Inherit from NSObject.

    class myClass: NSObject, AVAudioPlayerDelegate {
        var player = AVAudioPlayer()
    
        init(){
            player.delegate = self
        }
    
        func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
              print("The song ended")
        }
    }