@@ -22,19 +22,24 @@ import Foundation
2222/// static let shared: SimpleAnalytics = SimpleAnalytics(hostname: "mobileapp.yourdomain.com")
2323/// }
2424/// ````
25- public class SimpleAnalytics : NSObject {
25+ final public class SimpleAnalytics : NSObject {
2626 /// The hostname of the website in Simple Analytics the tracking should be send to. Without `https://`
2727 private let hostname : String
2828 private let userAgent : String
2929 private let userLanguage : String
3030 private let userTimezone : String
3131 /// The last date a unique visit was tracked.
3232 private var visitDate : Date ?
33- /// Key used to store the visit date in UserDefaults
34- private var visitDateKey = " simpleanalytics.visitdate "
3533
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+ }
3843
3944 /// Create the SimpleAnalytics instance that can be used to trigger events and pageviews.
4045 /// - Parameter hostname: The hostname as found in SimpleAnalytics, without `https://`
@@ -43,7 +48,7 @@ public class SimpleAnalytics: NSObject {
4348 self . userAgent = UserAgent . userAgentString ( )
4449 self . userLanguage = Locale . current. identifier
4550 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
4752 }
4853
4954 /// Track a pageview
@@ -118,13 +123,20 @@ public class SimpleAnalytics: NSObject {
118123 } else {
119124 // Last visit is not in today, so unique.
120125 self . visitDate = Date ( )
121- UserDefaults . standard. set ( visitDate, forKey: visitDateKey)
126+ UserDefaults . standard. set ( visitDate, forKey: Keys . visitDateKey)
122127 return true
123128 }
124129 } else {
130+ // No visit date yet, initialize it
125131 visitDate = Date ( )
126- UserDefaults . standard. set ( visitDate, forKey: visitDateKey)
132+ UserDefaults . standard. set ( visitDate, forKey: Keys . visitDateKey)
127133 return true
128134 }
129135 }
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+ }
130142}
0 commit comments