Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x1702076f0 of class AVPlayerItem was deallocated while key value observers were still registered with it. Current observation info: (
(.<)NSKeyValueObservance 0x174846360: Observer: 0x174846210, Key path: loadedTimeRanges, Options: Context: 0x0, Property: 0x1748462d0> )'
这是我在将 currentItem.loadedTimeRanges 观察器添加到我的 AVPlayer 后收到的错误
player = AVPlayer(url: videoUrl!)
playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = postVideoView.frame
playerLayer.frame.size.width = UIScreen.main.bounds.width
self.postVideoView.layer.addSublayer(playerLayer)
player?.play()
player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil, using: { (_) in
DispatchQueue.main.async {
self.player?.seek(to: kCMTimeZero)
self.player?.play()
}
})
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//this is when the player is ready and rendering frames
if keyPath == "currentItem.loadedTimeRanges" {
if let duration = player?.currentItem?.duration {
let seconds = CMTimeGetSeconds(duration)
let secondsText = Int(seconds) % 60
let minutesText = String(format: "%02d", Int(seconds) / 60)
videoLengthLabel.text = "\(minutesText):\(secondsText)"
}
}
}
最佳答案
你在哪里调用removeObserver
?目前看起来,如果您的顶级代码创建了一个新玩家并添加了一个观察者。如果这被调用两次,第一个实例中的观察者将仍然存在。因此,我希望顶部有以下行:
self.player?.removeObserver(self)
如果它没有被调用两次,代码中是否还有其他地方重新分配或释放了 self.player
?如果是这样,您应该首先调用 removeObserver
。
您还每次都向 NotificationCenter 添加一个新的观察者。这应该只被调用一次,或者在添加另一个之前调用 removeObserver
。
关于ios - 向玩家添加观察者时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45473621/