yattee/Model/Player/PiPDelegate.swift

70 lines
2.1 KiB
Swift
Raw Normal View History

2022-05-20 21:23:14 +00:00
import AVKit
import Foundation
2022-08-05 20:37:38 +00:00
import SwiftUI
2022-05-20 21:23:14 +00:00
final class PiPDelegate: NSObject, AVPictureInPictureControllerDelegate {
var player: PlayerModel!
func pictureInPictureController(
_: AVPictureInPictureController,
failedToStartPictureInPictureWithError error: Error
) {
print(error.localizedDescription)
}
func pictureInPictureControllerWillStartPictureInPicture(_: AVPictureInPictureController) {}
2022-05-21 20:58:11 +00:00
func pictureInPictureControllerDidStartPictureInPicture(_: AVPictureInPictureController) {
player?.playingInPictureInPicture = true
player?.avPlayerBackend.startPictureInPictureOnPlay = false
}
2022-05-20 21:23:14 +00:00
func pictureInPictureControllerDidStopPictureInPicture(_: AVPictureInPictureController) {
2022-05-29 20:13:21 +00:00
guard let player = player else {
return
}
if player.avPlayerBackend.switchToMPVOnPipClose,
2022-05-29 20:30:00 +00:00
!player.currentItem.isNil
{
2022-05-29 20:13:21 +00:00
DispatchQueue.main.async {
player.avPlayerBackend.switchToMPVOnPipClose = false
player.saveTime {
player.changeActiveBackend(from: .appleAVPlayer, to: .mpv)
2022-05-20 21:23:14 +00:00
}
}
}
2022-05-21 20:58:11 +00:00
2022-05-29 20:13:21 +00:00
player.playingInPictureInPicture = false
2022-05-20 21:23:14 +00:00
}
func pictureInPictureControllerWillStopPictureInPicture(_: AVPictureInPictureController) {}
func pictureInPictureController(
_: AVPictureInPictureController,
2022-05-21 20:58:11 +00:00
restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void
) {
2022-05-30 19:00:53 +00:00
var delay = 0.0
#if os(iOS)
2022-08-05 20:37:38 +00:00
if !player.presentingPlayer {
2022-05-30 19:00:53 +00:00
delay = 0.5
}
2022-08-05 20:37:38 +00:00
if player.currentItem.isNil {
delay = 1
}
2022-05-30 19:00:53 +00:00
#endif
2022-06-07 21:27:48 +00:00
if !player.currentItem.isNil, !player.musicMode {
2022-05-29 20:13:21 +00:00
player?.show()
}
2022-05-29 20:30:00 +00:00
2022-08-05 20:37:38 +00:00
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
withAnimation(.linear(duration: 0.3)) {
self?.player.playingInPictureInPicture = false
}
2022-05-29 14:38:37 +00:00
completionHandler(true)
}
2022-05-21 20:58:11 +00:00
}
2022-05-20 21:23:14 +00:00
}