i am trying to make a table view that plays multiple videos with AVPlayer
and AVPlayerItem
and i needed to addObserver to each AVPlayerItem
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()
}
}
}
Try to override 'prepareForReuse' function in your UITableViewCell subclass, and remove observer in that place.
override func prepareForReuse() {
super.prepareForReuse()
//remove observer here...
}