Add and remove observer from multiple AVPlayerItem on UITableViewCell

后端 未结 2 1444
醉酒成梦
醉酒成梦 2021-01-16 02:33

i am trying to make a table view that plays multiple videos with AVPlayer and AVPlayerItem and i needed to addObserver to each AVPlayerItem

相关标签:
2条回答
  • 2021-01-16 02:47

    So the best solution that ever worked for me is to subclass the AVPlayerItem and use protocol to delegate back to any class that conforms to AMPlayerItemDelegate

    here is how i did it

    protocol AMPlayerItemDelegate {
        func playbackLikelyToKeepUp()
    }
    
    class AMPlayerItem: AVPlayerItem {
    
       var delegate : MyPlayerItemDelegate?
    
       init(URL: NSURL) {
           super.init(asset: AVAsset(URL: URL) , automaticallyLoadedAssetKeys:[])
           self.addMyObservers()
       }
    
       deinit {
           self.removeMyObservers()
       }
    
       func addMyObservers() {
           print("Adding")
           self.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: [.New], context: nil)
       }
    
       func removeMyObservers() {
           print("Removing")
           self.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp", context: nil)
       }
    
       override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
           if keyPath == "playbackLikelyToKeepUp" {
               self.delegate?.playbackLikelyToKeepUp()
           }
       }
    
    }
    
    0 讨论(0)
  • 2021-01-16 02:55

    Try to override 'prepareForReuse' function in your UITableViewCell subclass, and remove observer in that place.

    override func prepareForReuse() {
        super.prepareForReuse()
    
        //remove observer here...
    }
    
    0 讨论(0)
提交回复
热议问题