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

别说谁变了你拦得住时间么 提交于 2019-12-12 20:20:57

问题


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.

Any Help would be appreciated


回答1:


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.




回答2:


Swift 5.1

Pass the item as your object:

// Stored property
let player = AVPlayer(url: videoUrl)

// When you are adding your video layer
let playerLayer = AVPlayerLayer(player: player)
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)

// add layer to view 

Then when you get that notification, here's how you can get the currentItem:

// Grab the item from the notification object and ensure its the same item as the current players item
if let item = notification.object as? AVPlayerItem,
    let currentItem = player.currentItem,
    item == currentItem {

    NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)

    // remove player from view or do whatever you need to do here
}     


来源:https://stackoverflow.com/questions/49403336/one-avplayers-avplayeritemdidplaytoendtime-action-executed-for-all-currently-pl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!