为什么AVAsset的状态更改观察者不起作用?

时间:2019-06-06 02:20:12

标签: ios swift avfoundation avplayeritem

我实现了以下code from Apple。旨在观察playerItem状态的变化。问题是由于某种原因它不起作用。准备就绪后,观察功能将无法运行。

所有相关代码如下:

func preloadVideo(media: Media) {
  //setup code, and then:
   media.playerItem1!.addObserver(self,
                                   forKeyPath: #keyPath(AVPlayerItem.status),
                                   options: [.old, .new],
                                   context: &playerItemContext)

}

观察方法:

private var playerItemContext = 0

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    // Only handle observations for the playerItemContext
    print("jdslfhjkfdhaldfahjkflhajfldashkjfdshkjlas")
    guard context == &playerItemContext else {
        super.observeValue(forKeyPath: keyPath, of: object,change: change, context: context)
        return
    }

    if keyPath == #keyPath(AVPlayerItem.status) {
        let status: AVPlayerItem.Status

        // Get the status change from the change dictionary
        if let statusNumber = change?[.newKey] as? NSNumber {
            status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
        } else {
            status = .unknown
        }
        print("dsfdgddgdggdgdgdgddsafdsaf434fdfdg433444343")

        // Switch over the status
        switch status {
        case .readyToPlay:
            //Stop animation, and go to p3
            print("dsfdsafdsaf434433444343")

            if goToVideo {
                print("Runinfdsh sahkbdsfhbsadfbadsfl")
                goToP3()
            }

            break
        // Player item is ready to play.
        case .failed: break
        // Player item failed. See error.
        case .unknown: break
            // Player item is not yet ready.
        @unknown default: break
            //fatal error
        }
    }
}

此方法将首先运行:

@objc func viewHandleTap(_ sender: UITapGestureRecognizer) {
    if selectedPost?.interimMedia.first?.imageURLString != nil || selectedPost?.interimMedia.first!.playerQueue?.status.rawValue == 1 {

        //do something
    } else {
        //status is 0 (video has not loaded yet)//load animation
        //this runs...
        goToVideo = true
    }
}

我如何使其起作用?目前,观察方法中没有任何内容可以打印。

如果还有另一种方法可以完成此操作,然后发布答案。

1 个答案:

答案 0 :(得分:1)

尝试通过将addObserver选项更新为[.old,.new,.initial,.prior]。

相关问题