Search code examples
iosvideo-streamingavplayertvosavplayerviewcontroller

AVPlayer pause not working TVOS


I am making a tvOS app. I have two tabs A and B in my application. Let say video is playing in tab A in a VC. I want to pause my current playing video when i switch the tabs from A->B. I am doing this in viewWillDisappear but the video only pauses for the first time. When i switch the tabs B->A again and hit play button on TV remote it plays but if i again try to switch the tabs A->B the video continues and it does not stops.

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)


        avplayerVC?.player?.rate = 0.0
        print("Player Playing Rate : ", "\(avplayerVC?.player?.rate)")
    }

I am using avPlayer.pause() method and avPlayer.rate = 0.0 to stop it but none of them works every time.

The log says that Player Playing Rate : Optional(0.0). but the video actually does not pauses. Here is my complete code.

    class PlayViewController : UIViewController {


        var avplayerVC : AVPlayerViewController?
        var videoUrlStr : String?

        override func viewDidLoad() {
            super.viewDidLoad()

            print("In PlayViewController View Did Load")

            avplayerVC = AVPlayerViewController()

            let avAsset = AVAsset(URL: NSURL.init(string: videoUrlStr!)!)
            let avPlayerItem = AVPlayerItem(asset: avAsset)
            avplayerVC?.player = AVPlayer(playerItem: avPlayerItem)

            avplayerVC?.player?.seekToTime(kCMTimeZero)
            print("Status 1: " +  "\(avplayerVC?.player?.status.rawValue)")

            print(self.view?.frame)

            // doesn't work
            avplayerVC?.view.frame =  self.view.frame


            self.view.addSubview((avplayerVC?.view!)!)
            avplayerVC?.player?.play()
        }


        override func viewWillDisappear(animated: Bool) {
            super.viewWillDisappear(animated)

            print("Changing rate")
            avplayerVC?.player?.rate = 0.0
            print("Player Playing Rate : ", "\(avplayerVC?.player?.rate)")
        }
   }

Any help will be highly appreciated.


Solution

  • I was having the same problem with AVPlayerViewController, maybe my answer helps you: here