@@ -26,6 +26,34 @@ public class Analytics {
26
26
27
27
public var timeline : Timeline
28
28
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
+
29
57
/// Initialize this instance of Analytics with a given configuration setup.
30
58
/// - Parameters:
31
59
/// - configuration: The configuration to use
@@ -40,6 +68,8 @@ public class Analytics {
40
68
41
69
storage. analytics = self
42
70
71
+ checkSharedInstance ( )
72
+
43
73
// Get everything running
44
74
platformStartup ( )
45
75
}
@@ -142,8 +172,8 @@ extension Analytics {
142
172
}
143
173
}
144
174
175
+ /// Returns a list of currently active flush policies.
145
176
public var flushPolicies : [ FlushPolicy ] {
146
-
147
177
get {
148
178
configuration. values. flushPolicies
149
179
}
@@ -332,3 +362,25 @@ extension Analytics {
332
362
track ( name: " Deep Link Opened " , properties: jsonProperties)
333
363
}
334
364
}
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