【问题标题】:Why does observer for status change of AVAsset not work?为什么 AVAsset 状态变化的观察者不起作用?
【发布时间】:2019-06-06 02:20:12
【问题描述】:

我实现了以下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
    }
}

我怎样才能让它工作?目前,观察方法中没有任何内容正在打印。

如果有其他方法可以完成此操作,请继续发布作为答案。

【问题讨论】:

  • 您将旋转角度设置为 90 度。您是否尝试将其设置为 0?

标签: ios swift avfoundation avplayeritem


【解决方案1】:

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

【讨论】:

  • 现在它运行该函数,但我在保护上下文中收到此错误:线程 5:同时访问 0x10b883638,但修改需要独占访问
  • 在目标的构建设置下。选择不强制从 Swift 编译器对内存的独占访问 - 代码生成
猜你喜欢
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多