From 8322d3a36cd29da543204c7844a49ef25ca575fa Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Mon, 8 Jul 2024 22:00:02 -0700 Subject: [PATCH] Fix gifv playback not continuing when returning from background Closes #506 --- Tusker/Views/Attachments/GifvPlayerView.swift | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Tusker/Views/Attachments/GifvPlayerView.swift b/Tusker/Views/Attachments/GifvPlayerView.swift index cf977777..bf605345 100644 --- a/Tusker/Views/Attachments/GifvPlayerView.swift +++ b/Tusker/Views/Attachments/GifvPlayerView.swift @@ -22,6 +22,7 @@ class GifvPlayerView: UIView { let controller: GifvController private var presentationSizeCancellable: AnyCancellable? + private var wasPlayingWhenSceneBackgrounded = false override var intrinsicContentSize: CGSize { controller.item.presentationSize @@ -45,4 +46,30 @@ class GifvPlayerView: UIView { fatalError("init(coder:) has not been implemented") } + override func willMove(toWindow newWindow: UIWindow?) { + super.willMove(toWindow: newWindow) + + if let oldWindow = window, + let oldScene = oldWindow.windowScene { + NotificationCenter.default.removeObserver(self, name: UIScene.didEnterBackgroundNotification, object: oldScene) + NotificationCenter.default.removeObserver(self, name: UIScene.willEnterForegroundNotification, object: oldScene) + } + + if let newWindow, + let newScene = newWindow.windowScene { + NotificationCenter.default.addObserver(self, selector: #selector(sceneDidEnterBackground), name: UIScene.didEnterBackgroundNotification, object: newScene) + NotificationCenter.default.addObserver(self, selector: #selector(sceneWillEnterForeground), name: UIScene.willEnterForegroundNotification, object: newScene) + } + } + + @objc private func sceneDidEnterBackground() { + wasPlayingWhenSceneBackgrounded = controller.player.rate > 0 + } + + @objc private func sceneWillEnterForeground() { + if wasPlayingWhenSceneBackgrounded { + controller.play() + } + } + }