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
This commit is contained in:
Stefan Ceriu
2026-09-30 12:43:21 +03:00
parent 38312b7473
commit a56a5c2819
@@ -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))
}
}
}