diff --git a/.changeset/brave-sessions-remain.md b/.changeset/brave-sessions-remain.md new file mode 100644 index 0000000000..90e493a73e --- /dev/null +++ b/.changeset/brave-sessions-remain.md @@ -0,0 +1,5 @@ +--- +"posthog-ios": patch +--- + +Keep tracking foreground and background transitions after `reset()`. Previously `reset()` unsubscribed the session manager from app lifecycle and UI events, so sessions stopped clearing in the background, or were never created again after a reset in the background, until the app restarted. diff --git a/PostHog/PostHogSessionManager.swift b/PostHog/PostHogSessionManager.swift index e670af0c95..332ea0534e 100644 --- a/PostHog/PostHogSessionManager.swift +++ b/PostHog/PostHogSessionManager.swift @@ -52,9 +52,6 @@ import Foundation func reset() { resetSession() - didBecomeActiveToken = nil - didEnterBackgroundToken = nil - applicationEventToken = nil } private let queue = DispatchQueue(label: "com.posthog.PostHogSessionManager", target: .global(qos: .utility)) diff --git a/PostHogTests/PostHogSessionManagerTest.swift b/PostHogTests/PostHogSessionManagerTest.swift index 8b2246c9d6..64c8ca7ea4 100644 --- a/PostHogTests/PostHogSessionManagerTest.swift +++ b/PostHogTests/PostHogSessionManagerTest.swift @@ -202,6 +202,41 @@ enum PostHogSessionManagerTest { #expect(newSessionId != originalSessionId) } + + @Test("reset() keeps tracking the app moving to the background") + func resetKeepsBackgroundTracking() throws { + let mockNow = MockDate() + now = { mockNow.date } + let posthog = getSut() + + mockAppLifecycle.simulateAppDidBecomeActive() + posthog.reset() + try #require(posthog.getSessionManager()?.getSessionId(readOnly: true) != nil) + + mockAppLifecycle.simulateAppDidEnterBackground() + mockNow.date.addTimeInterval(60 * 31) // past 30 minutes in the background (session should clear) + + #expect(posthog.getSessionManager()?.getSessionId() == nil) + } + + @Test("reset() keeps tracking the app moving to the foreground") + func resetKeepsForegroundTracking() throws { + let mockNow = MockDate() + now = { mockNow.date } + let posthog = getSut() + + mockAppLifecycle.simulateAppDidBecomeActive() + mockAppLifecycle.simulateAppDidEnterBackground() + posthog.reset() + let resetSessionId = try #require(posthog.getSessionManager()?.getSessionId(readOnly: true)) + + mockAppLifecycle.simulateAppDidBecomeActive() + mockNow.date.addTimeInterval(60 * 31) // past 30 minutes in the foreground (session should rotate, not clear) + let newSessionId = posthog.getSessionManager()?.getSessionId() + + #expect(newSessionId != nil) + #expect(newSessionId != resetSessionId) + } } @Suite("Test $session_id property in events")