Skip to content

Commit

Permalink
Make sure events after 30m have no session id if in background. Use l…
Browse files Browse the repository at this point in the history
…ock for sessionId read too
  • Loading branch information
mfclarke-cnx committed Feb 6, 2024
1 parent 6355178 commit d48c3ea
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions PostHog/PostHogSDK.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,13 @@ private let sessionChangeThreshold: TimeInterval = 60 * 30
if groups != nil, !groups!.isEmpty {
properties["$groups"] = groups!
}

if let sessionId = sessionId {
properties["$session_id"] = sessionId

var theSessionId: String?
sessionLock.withLock {
theSessionId = sessionId
}
if let theSessionId = theSessionId {
properties["$session_id"] = theSessionId
}

guard let flags = featureFlags?.getFeatureFlags() as? [String: Any] else {
Expand Down Expand Up @@ -371,6 +375,15 @@ private let sessionChangeThreshold: TimeInterval = 60 * 30
guard let queue = queue else {
return
}

// If events fire in the background after the threshold, they should no longer have a sessionId
if isInBackground && sessionId != nil,
let sessionLastTimestamp = sessionLastTimestamp,
Date().timeIntervalSince1970 - sessionLastTimestamp > sessionChangeThreshold {
sessionLock.withLock {
sessionId = nil
}
}

queue.add(PostHogEvent(
event: event,
Expand All @@ -380,12 +393,6 @@ private let sessionChangeThreshold: TimeInterval = 60 * 30
userPropertiesSetOnce: sanitizeDicionary(userPropertiesSetOnce),
groupProperties: sanitizeDicionary(groupProperties))
))

if !isInBackground {
sessionLock.withLock {
sessionLastTimestamp = Date().timeIntervalSince1970
}
}
}

@objc public func screen(_ screenTitle: String) {
Expand Down Expand Up @@ -814,6 +821,11 @@ private let sessionChangeThreshold: TimeInterval = 60 * 30

@objc func handleAppDidEnterBackground() {
captureAppBackgrounded()

sessionLock.withLock {
sessionLastTimestamp = Date().timeIntervalSince1970
}

isInBackground = true
}

Expand Down

0 comments on commit d48c3ea

Please sign in to comment.