Search code examples
iosswiftavplayer

One AVPlayer's AVPlayerItemDidPlayToEndTime action executed for all Currently playing videos


Problem : In collectionview cell which has player

if I play two Video simultaneously and seek first Video to end then AVPlayerItemDidPlayToEndTime fired for two times and both videos restarted

In collection view cell I have

override func awakeFromNib() {
        NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main, using: {[weak self]  (notification) in
            if self?.player != nil {
                self?.player?.seek(to: kCMTimeZero)
                self?.player?.play()
            }
        })
   }

and one play button action which play the video.
In cell I have slider to seek.

enter image description here

Any Help would be appreciated


Solution

  • Make sure that player and player?.currentItem are not equal to nil when you're registering for notifications. To me, it seems like one of them was nil and you're basically subscribing to all of the .AVPlayerItemDidPlayToEndTime notifications (since object is nil).

    To avoid that, subscribe to the notifications right after assigning AVAsset to the player.