Another Dude
Another Dude

Reputation: 1452

How to start picture in picture directly in app?

I have this simple code:

private func playVideo() {
    guard let videoURL = Bundle.main.url(
        forResource: "video",
        withExtension: "mp4"
    ) else {
        return
    }
        
    let avPlayerController = AVPlayerViewController()
    let player = AVPlayer(url: videoURL)
    avPlayerController.player = player
    avPlayerController.canStartPictureInPictureAutomaticallyFromInline = true
    present(avPlayerController, animated: true)
        
    avPlayerController.player?.play()
        
    let pipController = AVPictureInPictureController(
        playerLayer: .init(player: player)
    )
        
    pipController?.canStartPictureInPictureAutomaticallyFromInline = true
    pipController?.startPictureInPicture()
}

In the App Delegate:

try? AVAudioSession.sharedInstance().setCategory(.playback)
try? AVAudioSession.sharedInstance().setActive(true)

This starts effectively the picture in picture when the user leaves the app, and if he comes back by tapping the app icon, it stays running in the app. Now I would like to know if there is a way to directly start the picture-in-picture in the app, when a given view appears for example.

Upvotes: 0

Views: 61

Answers (1)

sonle
sonle

Reputation: 9161

There is no picture-in-picture in the app. Whenever you apply AVPictureInPictureController, the system determines which UI to dipslay automatically when you're in background mode (by adding Background Modes in Capability). In this case is AVPlayerLayer, or whatever content of any view controller that inherits to AVPictureInPictureVideoCallViewController if you use this kind of PiP adapter.

So, if you want a kind of PiP within the app, you need to do it yourself. Something like implementing a custom view that sticks on your screen's edges in the foreground mode and then additionally a UIPanGestureRecognizer to be able to drag/drop this view.

Upvotes: -1

Related Questions