From 519969eee09e8f674f6667366a68f075199c356b Mon Sep 17 00:00:00 2001 From: ronaldheft Date: Thu, 18 Aug 2022 16:20:28 -0400 Subject: [PATCH] Restore playback session on startup --- ios/App/App/plugins/AbsAudioPlayer.swift | 19 +++++++++++++++++++ ios/App/Shared/player/PlayerHandler.swift | 11 +++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/ios/App/App/plugins/AbsAudioPlayer.swift b/ios/App/App/plugins/AbsAudioPlayer.swift index 9b4cc9e7..760bb4af 100644 --- a/ios/App/App/plugins/AbsAudioPlayer.swift +++ b/ios/App/App/plugins/AbsAudioPlayer.swift @@ -24,10 +24,29 @@ public class AbsAudioPlayer: CAPPlugin { NotificationCenter.default.addObserver(self, selector: #selector(onPlaybackFailed), name: NSNotification.Name(PlayerEvents.failed.rawValue), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(onLocalMediaProgressUpdate), name: NSNotification.Name(PlayerEvents.localProgress.rawValue), object: nil) + // Restore the playack session when plugin loads + Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(restorePlaybackSession), userInfo: nil, repeats: false) + self.bridge?.webView?.allowsBackForwardNavigationGestures = true; } + @objc func restorePlaybackSession() { + // We don't need to restore if we have an active session + guard PlayerHandler.getPlaybackSession() == nil else { return } + + do { + // Fetch the most recent active session + let activeSession = try Realm().objects(PlaybackSession.self).where({ $0.isActiveSession == true }).last + if let activeSession = activeSession { + try self.startPlaybackSession(activeSession, playWhenReady: false) + } + } catch { + NSLog("Failed to restore playback session") + debugPrint(error) + } + } + @objc func startPlaybackSession(_ session: PlaybackSession, playWhenReady: Bool, playbackRate: Float = 1.0) throws { guard let libraryItemId = session.libraryItemId else { throw PlayerError.libraryItemIdNotSpecified } diff --git a/ios/App/Shared/player/PlayerHandler.swift b/ios/App/Shared/player/PlayerHandler.swift index 0cc5107f..e979e1f7 100644 --- a/ios/App/Shared/player/PlayerHandler.swift +++ b/ios/App/Shared/player/PlayerHandler.swift @@ -69,12 +69,11 @@ class PlayerHandler { } private static func cleanupOldSessions(currentSessionId: String?) { - if let currentSessionId = currentSessionId { - let realm = try! Realm() - let oldSessions = realm.objects(PlaybackSession.self) - .where({ $0.isActiveSession == true && $0.id != currentSessionId }) - try! realm.write { - for s in oldSessions { + let realm = try! Realm() + let oldSessions = realm.objects(PlaybackSession.self) .where({ $0.isActiveSession == true }) + try! realm.write { + for s in oldSessions { + if s.id != currentSessionId { s.isActiveSession = false } }