yattee/Model/Player/PiPDelegate.swift

65 lines
2.0 KiB
Swift
Raw Normal View History

2022-05-20 21:23:14 +00:00
import AVKit
2022-08-26 20:17:21 +00:00
import Defaults
2022-05-20 21:23:14 +00:00
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) {
2022-09-28 14:27:01 +00:00
guard let player else { return }
2022-08-26 20:17:21 +00:00
player.playingInPictureInPicture = true
player.avPlayerBackend.startPictureInPictureOnPlay = false
player.avPlayerBackend.startPictureInPictureOnSwitch = false
player.controls.objectWillChange.send()
if Defaults[.closePlayerOnOpeningPiP] { Delay.by(0.1) { player.hide() } }
2022-05-21 20:58:11 +00:00
}
2022-05-20 21:23:14 +00:00
func pictureInPictureControllerDidStopPictureInPicture(_: AVPictureInPictureController) {
2022-09-28 14:27:01 +00:00
guard let player else { return }
2022-05-29 20:13:21 +00:00
player.playingInPictureInPicture = false
2022-08-26 20:17:21 +00:00
player.controls.objectWillChange.send()
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
}