Почему не работает наблюдатель за изменением статуса AVAsset?

Я реализовал следующий код от 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
    }
}

Как я могу заставить его работать? В настоящее время в методе наблюдения ничего не печатается.

Если есть другой способ сделать это, продолжайте и опубликуйте как ответ.


person Community    schedule 06.06.2019    source источник
comment
Вы устанавливаете угол поворота 90 градусов. Вы пробовали установить его на 0?   -  person Adrian    schedule 06.06.2019


Ответы (1)


Попробуйте обновить параметры addObserver до [.old, .new, .initial, .prior].

person Arun Ammannaya    schedule 13.06.2019
comment
Теперь он запускает функцию, но я получаю эту ошибку в контексте защиты: Тема 5: одновременный доступ к 0x10b883638, но для модификации требуется монопольный доступ - person ; 13.06.2019
comment
В настройках сборки цели. Выберите No Enforcement для монопольного доступа к памяти из компилятора Swift — генерация кода - person Arun Ammannaya; 14.06.2019