AVPlayer+AVPictureInPictureController doesn't automatically start picture-in-picture when backgrounding the app (iOS 14 beta 7)

When creating a custom video player using the AVPlayer+AVPlayerLayer+AVPictureInPictureController in iOS 14 (beta 7) the video does not automatically pip when the app enters the background if player.start() is called from a UIButton action. However if player.start() is called from viewDidLoad this is not a problem.

The issue does not reproduce using the AVPlayerViewController which seems to indicate a problem with the AVPictureInPictureController on iOS 14 in general.

The issue also did not reproduce on beta 5, but started appearing on beta 6 -- probably a iOS 14 regression.

Some sample/pseudo code to illustrate the problem.

Code Block
let player = AVPlayer(url: URL(string: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")!)
let playerView = PlayerView()
playerView.playerLayer.player = player
let audioSession = AVAudioSession.sharedInstance()
try? audioSession.setCategory(.playback)
try? audioSession.setMode(.moviePlayback)
try? audioSession.setActive(true)
let pictureInPictureController = AVPictureInPictureController(playerLayer: playerView.playerLayer)
@IBAction func playButtonTapped(_ sender: Any) {
player.play() /* the video will not automatically pip when the app is entering the background */
}
class PlayerView: UIView {
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
var playerLayer: AVPlayerLayer! {
return layer as? AVPlayerLayer
}
}


Is anyone else struggling with this? Any potential workarounds?

I've also filed this as a feedback request (rdar://8620271) but figured I would ask here in the community forums as well.
I'm seeing the same thing here. Using AVPictureInPictureController, it does not start pip automatically when app goes to background, unless the player was started from viewDidLoad. Pip works if calling startPictureInPicture from a UIButton, but that's it, it's not automatic... Also checked the "Start Pip Automatically" option in Settings.

I'm not sure what is missing
We have determined the root cause of the problems
  1. AVAudioSession.sharedInstance().setActive(true) must be called before the AVPictureInPictureController is initialised.

  2. The frame size for the AVPlayerLayer must have a aspect ratio no greater than 16/9 (filed as a separate bug, rdar//8689203)

I hope this will be useful information to others experiencing similar issues. While both of these issues seems intentional by Apple, these side effects need to be documented or trigger proper asserts and/or log statements so developers can solve the issues on their end.
AVPlayer+AVPictureInPictureController doesn't automatically start picture-in-picture when backgrounding the app (iOS 14 beta 7)
 
 
Q