From a56a5c281961e15e00ff8f80529c66a3d82f5f62 Mon Sep 17 00:00:00 2001 From: Stefan Ceriu Date: Wed, 30 Sep 2026 12:43:21 +0300 Subject: [PATCH] Wait for the session restore in background app refresh When iOS relaunches a terminated app for the task, the session is still being restored asynchronously when the refresh starts. Wait up to 5 seconds for the restore to finish, bailing out early if the app isn't restoring a session (e.g. signed out or the restore failed). # Conflicts: # ElementX/Sources/Application/AppCoordinator.swift --- .../Sources/Application/AppCoordinator.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/ElementX/Sources/Application/AppCoordinator.swift b/ElementX/Sources/Application/AppCoordinator.swift index 6b0d7d7be..c4967419e 100644 --- a/ElementX/Sources/Application/AppCoordinator.swift +++ b/ElementX/Sources/Application/AppCoordinator.swift @@ -1302,7 +1302,11 @@ private extension AppCoordinator { } } + await waitForSessionRestore() + guard let userSession else { + MXLog.info("Background app refresh: no user session, giving up.") + task.setTaskCompleted(success: false) return } @@ -1393,3 +1397,15 @@ private extension AppCoordinator { task.setTaskCompleted(success: true) } } + +private extension AppCoordinator { + /// When iOS relaunches a terminated app for a background task, the session is still being restored asynchronously. + func waitForSessionRestore() async { + let deadline = ContinuousClock.now + .seconds(5) + while userSession == nil, + stateMachine.state == .initial || stateMachine.state == .restoringSession, + ContinuousClock.now < deadline { + try? await Task.sleep(for: .milliseconds(100)) + } + } +}