@@ -407,21 +407,24 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele
407407 return
408408 }
409409
410- taskId = sharedApplication . beginBackgroundTask { [ weak self] in
410+ let completionHandler : ( ) -> Void = { [ weak self] in
411411 guard let self = self else { return }
412412
413413#if DECIDE
414414 self . readWriteLock. write {
415415 self . decideInstance. decideFetched = false
416416 }
417417#endif // DECIDE
418-
419- sharedApplication. endBackgroundTask ( self . taskId)
420- self . taskId = UIBackgroundTaskIdentifier . invalid
418+ if self . taskId != UIBackgroundTaskIdentifier . invalid {
419+ sharedApplication. endBackgroundTask ( self . taskId)
420+ self . taskId = UIBackgroundTaskIdentifier . invalid
421+ }
421422 }
422423
424+ taskId = sharedApplication. beginBackgroundTask ( expirationHandler: completionHandler)
425+
423426 if flushOnBackground {
424- flush ( )
427+ flush ( completion : completionHandler )
425428 }
426429 }
427430
@@ -853,10 +856,16 @@ extension MixpanelInstance {
853856 }
854857 trackingQueue. async { [ weak self, completion] in
855858 guard let self = self else {
859+ if let completion = completion {
860+ DispatchQueue . main. async ( execute: completion)
861+ }
856862 return
857863 }
858864
859865 if let shouldFlush = self . delegate? . mixpanelWillFlush ( self ) , !shouldFlush {
866+ if let completion = completion {
867+ DispatchQueue . main. async ( execute: completion)
868+ }
860869 return
861870 }
862871
@@ -870,6 +879,9 @@ extension MixpanelInstance {
870879
871880 self . networkQueue. async { [ weak self, completion] in
872881 guard let self = self else {
882+ if let completion = completion {
883+ DispatchQueue . main. async ( execute: completion)
884+ }
873885 return
874886 }
875887 self . flushQueue ( eventQueue, type: . events)
0 commit comments