@@ -26,6 +26,34 @@ public class Analytics {
2626
2727 public var timeline : Timeline
2828
29+ static internal let deadInstance = " DEADINSTANCE "
30+ static internal weak var firstInstance : Analytics ? = nil
31+
32+ /**
33+ This method isn't a traditional singleton implementation. It's provided here
34+ to ease migration from analytics-ios to analytics-swift. Rather than return a
35+ singleton, it returns the first instance of Analytics created, OR an instance
36+ who's writekey is "DEADINSTANCE".
37+
38+ In the case of a dead instance, an assert will be thrown when in DEBUG builds to
39+ assist developers in knowning that `shared()` is being called too soon.
40+ */
41+ static func shared( ) -> Analytics {
42+ if let a = firstInstance {
43+ if a. isDead == false {
44+ return a
45+ }
46+ }
47+
48+ #if DEBUG
49+ if isUnitTesting == false {
50+ assert ( true == false , " An instance of Analytice does not exist! " )
51+ }
52+ #endif
53+
54+ return Analytics ( configuration: Configuration ( writeKey: deadInstance) )
55+ }
56+
2957 /// Initialize this instance of Analytics with a given configuration setup.
3058 /// - Parameters:
3159 /// - configuration: The configuration to use
@@ -40,6 +68,8 @@ public class Analytics {
4068
4169 storage. analytics = self
4270
71+ checkSharedInstance ( )
72+
4373 // Get everything running
4474 platformStartup ( )
4575 }
@@ -142,8 +172,8 @@ extension Analytics {
142172 }
143173 }
144174
175+ /// Returns a list of currently active flush policies.
145176 public var flushPolicies : [ FlushPolicy ] {
146-
147177 get {
148178 configuration. values. flushPolicies
149179 }
@@ -332,3 +362,25 @@ extension Analytics {
332362 track ( name: " Deep Link Opened " , properties: jsonProperties)
333363 }
334364}
365+
366+ // MARK: Private Stuff
367+
368+ extension Analytics {
369+ private func checkSharedInstance( ) {
370+ // is firstInstance a dead one? If so, override it.
371+ if let firstInstance = Self . firstInstance {
372+ if firstInstance. isDead {
373+ Self . firstInstance = self
374+ }
375+ }
376+ // is firstInstance nil? If so, set it.
377+ if Self . firstInstance == nil {
378+ Self . firstInstance = self
379+ }
380+ }
381+
382+ /// Determines if an instance is dead.
383+ internal var isDead : Bool {
384+ return configuration. values. writeKey == Self . deadInstance
385+ }
386+ }
0 commit comments