@@ -22,19 +22,24 @@ import Foundation
22
22
/// static let shared: SimpleAnalytics = SimpleAnalytics(hostname: "mobileapp.yourdomain.com")
23
23
/// }
24
24
/// ````
25
- public class SimpleAnalytics : NSObject {
25
+ final public class SimpleAnalytics : NSObject {
26
26
/// The hostname of the website in Simple Analytics the tracking should be send to. Without `https://`
27
27
private let hostname : String
28
28
private let userAgent : String
29
29
private let userLanguage : String
30
30
private let userTimezone : String
31
31
/// The last date a unique visit was tracked.
32
32
private var visitDate : Date ?
33
- /// Key used to store the visit date in UserDefaults
34
- private var visitDateKey = " simpleanalytics.visitdate "
35
33
36
- /// Defines if the user is opted out. When set to `true`, all tracking will be skipped. This is not persisted between sessions.
37
- public var isOptedOut : Bool = false
34
+ /// Defines if the user is opted out. When set to `true`, all tracking will be skipped. This is persisted between sessions.
35
+ public var isOptedOut : Bool {
36
+ get {
37
+ UserDefaults . standard. bool ( forKey: Keys . optedOutKey)
38
+ }
39
+ set {
40
+ UserDefaults . standard. setValue ( newValue, forKey: Keys . optedOutKey)
41
+ }
42
+ }
38
43
39
44
/// Create the SimpleAnalytics instance that can be used to trigger events and pageviews.
40
45
/// - Parameter hostname: The hostname as found in SimpleAnalytics, without `https://`
@@ -43,7 +48,7 @@ public class SimpleAnalytics: NSObject {
43
48
self . userAgent = UserAgent . userAgentString ( )
44
49
self . userLanguage = Locale . current. identifier
45
50
self . userTimezone = TimeZone . current. identifier
46
- self . visitDate = UserDefaults . standard. object ( forKey: visitDateKey) as? Date
51
+ self . visitDate = UserDefaults . standard. object ( forKey: Keys . visitDateKey) as? Date
47
52
}
48
53
49
54
/// Track a pageview
@@ -118,13 +123,20 @@ public class SimpleAnalytics: NSObject {
118
123
} else {
119
124
// Last visit is not in today, so unique.
120
125
self . visitDate = Date ( )
121
- UserDefaults . standard. set ( visitDate, forKey: visitDateKey)
126
+ UserDefaults . standard. set ( visitDate, forKey: Keys . visitDateKey)
122
127
return true
123
128
}
124
129
} else {
130
+ // No visit date yet, initialize it
125
131
visitDate = Date ( )
126
- UserDefaults . standard. set ( visitDate, forKey: visitDateKey)
132
+ UserDefaults . standard. set ( visitDate, forKey: Keys . visitDateKey)
127
133
return true
128
134
}
129
135
}
136
+
137
+ /// Keys used to store things in UserDefaults
138
+ internal struct Keys {
139
+ static let visitDateKey = " simpleanalytics.visitdate "
140
+ static let optedOutKey = " simpleanalytics.isoptedout "
141
+ }
130
142
}
0 commit comments