ios - 向玩家添加观察者时出错

标签 ios swift xcode avplayer

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/

相关文章:

ios - Segue 仅在选择另一个表行时执行

ios - 如何在 Facebook 上从表格 View 共享内容

ios - 将对象传递给自定义注释 View

ios - 重试 URLSession dataTask 的模式?

ios 8 Swift - 带有嵌入式 CollectionView 的 TableView

c - 文字中的非 ASCII、非 Unicode 字符

ios - 无法在 bundle 中找到名为 'Main' 的 Storyboard,Xcode 7

不使用 Storyboard 的 iOS7 segue

ios - swift 3 : Realm creates additional object instead of updating the exisiting one

ios - 如何在 Interface Builder 预览 Storyboard中显示导航栏(助理编辑器)