Search code examples
iosswiftswiftuiavkit

[iOS]: Picture in picture not working in UIKit class using UIViewControllerRepresentable


I'm trying to implement a picture in picture custom player, with the following setup up:

private func setupCustomPlayer(){
    let playerLayer = AVPlayerLayer(player: player)
        
    playerLayer.frame = videoView.bounds
    playerLayer.videoGravity = .resizeAspectFill
    videoView.layer.addSublayer(playerLayer)
    
    pip = AVPictureInPictureController(playerLayer: playerLayer)
    pip.canStartPictureInPictureAutomaticallyFromInline = true
    pip.delegate = self
    
    player?.play()
}

However, the picture in picture does not working, also I set up the audio session in app delegate:

    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(.playback, mode: .moviePlayback)
    } catch {
        print("Setting category to AVAudioSessionCategoryPlayback failed.")
    }

The question is. what could be happening. I'm using this source code to guide me: https://github.com/sharmavipin11289/PIP, but I don't have lucky.

There's my UIViewControllerRepresentable class:

func makeUIViewController(context: Context) -> some PlayerViewController {
    let vc = PlayerViewController(url: url, showsHelp: false) {
        fullscreen.toggle()
        if fullscreen {
            self.changeOrientation(to: .landscapeLeft)
        } else {
            self.changeOrientation(to: .portrait)
        }
    }
    return vc
}

func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
    
}

Can anybody help me?

Best Regards


Solution

  • The issue can be solved upgrading from iOS 14 to iOS 16 and using the following audio session in App Delegate:

    let audioSession = AVAudioSession.sharedInstance()
     do {
         try audioSession.setCategory(.playback)
         try audioSession.setActive(true, options: [])
     } catch {
         print("Setting category to AVAudioSessionCategoryPlayback failed.")
     }