Llg Llg - 28 days ago 11
iOS Question

Swift: Detect video end

I have to play some videos in my swift application. The video is working perfectly but I want to detect when the video is ended. I searched about that then I found that the

NotificationCenter
is the solution for that. I used this code but my application crash at the end of the video.

This is my code:

func playVideo(url: NSURL){
let player = AVPlayer(url: url as URL)

NotificationCenter.default.addObserver(self, selector: Selector(("playerDidFinishPlaying")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
player.play()
}

func playerDidFinishPlaying(note: NSNotification) {
print("Video Finished")
}


The error is:

[myApp.myViewController playerDidFinishPlaying]: unrecognized selector sent to instance 0x79669740


Any help please?

Answer

Because your selector is wrong, obviously. You are saying:

Selector(("playerDidFinishPlaying"))

But that is not the Objective-C name of your method.

Clearly, you don't know how to make the Objective-C name of your method. And you don't have to! This is exactly what #selector syntax solves. Just use it:

#selector(playerDidFinishPlaying)

And now it will work, because Swift will solve the problem you don't know how to solve.

Comments