yattee/Model/Player/PiPDelegate.swift

72 lines
2.1 KiB
Swift
Raw Permalink 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 {
2023-05-20 20:49:10 +00:00
var player: PlayerModel { .shared }
2022-05-20 21:23:14 +00:00
func pictureInPictureController(
_: AVPictureInPictureController,
failedToStartPictureInPictureWithError error: Error
) {
print(error.localizedDescription)
}
func pictureInPictureControllerWillStartPictureInPicture(_: AVPictureInPictureController) {}
2022-05-21 20:58:11 +00:00
func pictureInPictureControllerDidStartPictureInPicture(_: AVPictureInPictureController) {
2023-05-20 20:49:10 +00:00
player.play()
2022-08-26 20:17:21 +00:00
player.playingInPictureInPicture = true
player.avPlayerBackend.startPictureInPictureOnPlay = false
player.avPlayerBackend.startPictureInPictureOnSwitch = false
player.controls.objectWillChange.send()
2023-05-20 20:49:10 +00:00
if Defaults[.closePlayerOnOpeningPiP] { Delay.by(0.1) { self.player.hide() } }
2022-05-21 20:58:11 +00:00
}
2022-05-20 21:23:14 +00:00
func pictureInPictureControllerDidStopPictureInPicture(_: AVPictureInPictureController) {
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
}
2023-05-22 20:48:11 +00:00
func pictureInPictureControllerWillStopPictureInPicture(_: AVPictureInPictureController) {
player.show()
}
2022-05-20 21:23:14 +00:00
func pictureInPictureController(
_: AVPictureInPictureController,
2022-05-21 20:58:11 +00:00
restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void
) {
2023-05-20 20:49:10 +00:00
let wasPlaying = player.isPlaying
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 {
2023-05-20 20:49:10 +00:00
player.show()
2022-05-29 20:13:21 +00:00
}
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
}
2023-05-20 20:49:10 +00:00
if wasPlaying {
Delay.by(1) {
self?.player.play()
}
}
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
}