Search code examples
iosswiftavplayeravplayeritemavkit

How to detect which video ended when using multiple AVPlayers?


I am playing two videos side by side on screen so I have two instances of AVPlayer. I am detecting end of video playback using notification which is working fine. My selector(playerDidFinishPlaying) is getting called for both videos when they end.

NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil) 

Now my problem is in the selector(playerDidFinishPlaying), I want to detect for which avplayer it got called? How can I uniquely identify the AVPlayer whose video ended?


Solution

  • Another idea. Updated @black_pearl's method

    Different notification registration , with different notification methods.

        var player = AVPlayer()
        var playerTwo = AVPlayer()
    
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
            NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlay(_:)), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
            NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishMusic(_:)), name: .AVPlayerItemDidPlayToEndTime, object: playerTwo.currentItem)
    
        }
    
    
           @objc func playerDidFinishPlay(_ noti: Notification) {
               if let p = noti.object as? AVPlayerItem, p == player.currentItem {
                    print("1")
               }
           }
    
    
        @objc func playerDidFinishMusic(_ noti: Notification) {
            if let p = noti.object as? AVPlayerItem, p == playerTwo.currentItem{
                print("2")
            }
        }