-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathCustomerIO.swift
425 lines (353 loc) · 13.6 KB
/
CustomerIO.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import CioInternalCommon
import Foundation
public protocol CustomerIOInstance: AutoMockable {
var siteId: String? { get }
/// Get the current configuration options set for the SDK.
var config: SdkConfig? { get }
func identify(
identifier: String,
body: [String: Any]
)
// sourcery:Name=identifyEncodable
// sourcery:DuplicateMethod=identify
func identify<RequestBody: Encodable>(
identifier: String,
// sourcery:Type=AnyEncodable
// sourcery:TypeCast="AnyEncodable(body)"
body: RequestBody
)
var registeredDeviceToken: String? { get }
func clearIdentify()
func track(
name: String,
data: [String: Any]
)
// sourcery:Name=trackEncodable
// sourcery:DuplicateMethod=track
func track<RequestBody: Encodable>(
name: String,
// sourcery:Type=AnyEncodable
// sourcery:TypeCast="AnyEncodable(data)"
data: RequestBody?
)
func screen(
name: String,
data: [String: Any]
)
// sourcery:Name=screenEncodable
// sourcery:DuplicateMethod=screen
func screen<RequestBody: Encodable>(
name: String,
// sourcery:Type=AnyEncodable
// sourcery:TypeCast="AnyEncodable(data)"
data: RequestBody?
)
var profileAttributes: [String: Any] { get set }
var deviceAttributes: [String: Any] { get set }
func registerDeviceToken(_ deviceToken: String)
func deleteDeviceToken()
func trackMetric(
deliveryID: String,
event: Metric,
deviceToken: String
)
}
public extension CustomerIOInstance {
func identify(
identifier: String
) {
identify(identifier: identifier, body: EmptyRequestBody())
}
func track(
name: String
) {
track(name: name, data: EmptyRequestBody())
}
func screen(
name: String
) {
screen(name: name, data: EmptyRequestBody())
}
}
/**
Welcome to the Customer.io iOS SDK!
This class is where you begin to use the SDK.
You must call `CustomerIO.initialize` to use the features of the SDK.
*/
public class CustomerIO: CustomerIOInstance {
/// The current version of the Customer.io SDK.
public static var version: String {
SdkVersion.version
}
public var siteId: String? {
diGraph?.sdkConfig.siteId
}
/**
Singleton shared instance of `CustomerIO`. Convenient way to use the SDK.
Note: Don't forget to call `CustomerIO.initialize()` before using this!
*/
@Atomic public private(set) static var shared = CustomerIO()
// Only assign a value to this *when the SDK is initialzied*.
// It's assumed that if this instance is not-nil, the SDK has been initialized.
// Tip: Use `SdkInitializedUtil` in modules to see if the SDK has been initialized and get data it needs.
private var implementation: CustomerIOInstance?
// The 1 place that DiGraph is strongly stored in memory for the SDK.
// Exposed for `SdkInitializedUtil`. Not recommended to use this property directly.
var diGraph: DIGraph?
// strong reference to repository to prevent garbage collection as it runs tasks in async.
@Atomic private var cleanupRepository: CleanupRepository?
// private constructor to force use of singleton API
private init() {}
// Constructor for unit testing. Just for overriding dependencies and not running logic.
// See CustomerIO.shared.initializeIntegrationTests for integration testing
init(implementation: CustomerIOInstance, diGraph: DIGraph) {
self.implementation = implementation
self.diGraph = diGraph
}
/**
Make testing the singleton `instance` possible.
Note: It's recommended to delete app data before doing this to prevent loading persisted credentials
*/
static func resetSharedInstance() {
shared = CustomerIO()
}
// Special initialize used for integration tests. Mostly to be able to share a DI graph
// between the SDK classes and test class. Runs all the same logic that the production `intialize` does.
static func initializeIntegrationTests(
diGraph: DIGraph
) {
let implementation = CustomerIOImplementation(diGraph: diGraph)
shared = CustomerIO(implementation: implementation, diGraph: diGraph)
shared.postInitialize(diGraph: diGraph)
}
/**
Initialize the shared `instance` of `CustomerIO`.
Call this function when your app launches, before using `CustomerIO.instance`.
*/
@available(iOSApplicationExtension, unavailable)
public static func initialize(
siteId: String,
apiKey: String,
region: Region,
configure configureHandler: ((inout SdkConfig) -> Void)?
) {
var newSdkConfig = SdkConfig.Factory.create(siteId: siteId, apiKey: apiKey, region: region)
if let configureHandler = configureHandler {
configureHandler(&newSdkConfig)
}
initialize(config: newSdkConfig)
if newSdkConfig.autoTrackScreenViews {
// Setting up screen view tracking is not available for rich push (Notification Service Extension).
// Only call this code when not possibly being called from a NSE.
shared.setupAutoScreenviewTracking()
}
}
/**
Initialize the shared `instance` of `CustomerIO`.
Call this function in your Notification Service Extension for the rich push feature.
*/
@available(iOS, unavailable)
@available(iOSApplicationExtension, introduced: 13.0)
public static func initialize(
siteId: String,
apiKey: String,
region: Region,
configure configureHandler: ((inout NotificationServiceExtensionSdkConfig) -> Void)?
) {
var newSdkConfig = NotificationServiceExtensionSdkConfig.Factory.create(siteId: siteId, apiKey: apiKey, region: region)
if let configureHandler = configureHandler {
configureHandler(&newSdkConfig)
}
initialize(config: newSdkConfig.toSdkConfig())
}
// private shared logic initialize to avoid copy/paste between the different
// public initialize functions.
private static func initialize(
config: SdkConfig
) {
let newDiGraph = DIGraph(sdkConfig: config)
shared.diGraph = newDiGraph
shared.implementation = CustomerIOImplementation(diGraph: newDiGraph)
shared.postInitialize(diGraph: newDiGraph)
}
// Contains all logic shared between all of the initialize() functions.
func postInitialize(diGraph: DIGraph) {
let hooks = diGraph.hooksManager
let threadUtil = diGraph.threadUtil
let logger = diGraph.logger
let siteId = diGraph.sdkConfig.siteId
// Register Tracking module hooks now that the module is being initialized.
hooks.add(key: .tracking, provider: TrackingModuleHookProvider())
// Register the device token during SDK initialization to address device registration issues
// arising from lifecycle differences between wrapper SDKs and native SDK.
let globalDataStore = diGraph.globalDataStore
if let token = globalDataStore.pushDeviceToken {
registerDeviceToken(token)
}
// Only run async operations 1 time, no matter how many times the SDK initializes.
// Exceptions can occur when:
// - Instance of CleanupRepository created in thread A. Schedules async operation to occur on background thread.
// - New instance of CleanupRepository created by thread B.
// - Async operation in background thread begins. Tries to reference repository instance that was created by thread A, where it got scheduled.
// - Memory exception thrown because old repository instance from thread A is gone.
if cleanupRepository == nil { // Using cleanupRepository instance to determine if this has been run before.
cleanupRepository = diGraph.cleanupRepository
// run cleanup in background to prevent locking the UI thread
threadUtil.runBackground { [weak self] in
// Crash occurs on line below if repository gets re-assigned
self?.cleanupRepository?.cleanup()
}
}
logger
.info(
"Customer.io SDK \(SdkVersion.version) initialized and ready to use for site id: \(siteId)"
)
}
/**
Use `registeredDeviceToken` to fetch the current FCM/APN device token.
This returns an optional string value.
Example use:
```
CustomerIO.shared.registeredDeviceToken
```
*/
public var registeredDeviceToken: String? {
implementation?.registeredDeviceToken
}
public var config: SdkConfig? {
implementation?.config
}
/**
Modify attributes to an already identified profile.
Note: The getter of this field returns an empty dictionary. This is a setter only field.
*/
public var profileAttributes: [String: Any] {
get {
implementation?.profileAttributes ?? [:]
}
set {
implementation?.profileAttributes = newValue
}
}
/**
Use `deviceAttributes` to provide additional and custom device attributes
apart from the ones the SDK is programmed to send to customer workspace.
Example use:
```
CustomerIO.shared.deviceAttributes = ["foo" : "bar"]
```
*/
public var deviceAttributes: [String: Any] {
get {
implementation?.deviceAttributes ?? [:]
}
set {
implementation?.deviceAttributes = newValue
}
}
/**
Identify a customer (aka: Add or update a profile).
[Learn more](https://customer.io/docs/identifying-people/) about identifying a customer in Customer.io
Note: You can only identify 1 profile at a time in your SDK. If you call this function multiple times,
the previously identified profile will be removed. Only the latest identified customer is persisted.
- Parameters:
- identifier: ID you want to assign to the customer.
This value can be an internal ID that your system uses or an email address.
[Learn more](https://customer.io/docs/api/#operation/identify)
- body: Request body of identifying profile. Use to define user attributes.
*/
public func identify<RequestBody: Encodable>(
identifier: String,
body: RequestBody
) {
implementation?.identify(identifier: identifier, body: body)
}
public func identify(identifier: String, body: [String: Any]) {
implementation?.identify(identifier: identifier, body: body)
}
/**
Stop identifying the currently persisted customer. All future calls to the SDK will no longer
be associated with the previously identified customer.
Note: If you simply want to identify a *new* customer, this function call is optional. Simply
call `identify()` again to identify the new customer profile over the existing.
If no profile has been identified yet, this function will ignore your request.
*/
public func clearIdentify() {
implementation?.clearIdentify()
}
/**
Track an event
[Learn more](https://customer.io/docs/events/) about events in Customer.io
- Parameters:
- name: Name of the event you want to track.
- data: Optional event body data
*/
public func track<RequestBody: Encodable>(
name: String,
data: RequestBody?
) {
implementation?.track(name: name, data: data)
}
public func track(name: String, data: [String: Any]) {
implementation?.track(name: name, data: data)
}
public func screen(name: String, data: [String: Any]) {
implementation?.screen(name: name, data: data)
}
/**
Track a a screen view
[Learn more](https://customer.io/docs/events/) about events in Customer.io
- Parameters:
- name: Name of the currently active screen
- data: Optional event body data
*/
public func screen<RequestBody: Encodable>(
name: String,
data: RequestBody
) {
implementation?.screen(name: name, data: data)
}
func automaticScreenView(
name: String,
data: [String: Any]
) {
guard let logger = diGraph?.logger else {
return
}
automaticScreenView(name: name, data: StringAnyEncodable(logger: logger, data))
}
// Designed to be called from swizzled methods for automatic screen tracking.
// Because swizzled functions are not able to determine what siteId instance of
// the SDK the app is using, we simply call `screen()` on all siteIds of the SDK
// and if automatic screen view tracking is not setup for that siteId, the function
// call to the instance will simply be ignored.
func automaticScreenView<RequestBody: Encodable>(
name: String,
data: RequestBody
) {
implementation?.screen(name: name, data: data)
}
/**
Register a new device token with Customer.io, associated with the current active customer. If there
is no active customer, this will fail to register the device
*/
public func registerDeviceToken(_ deviceToken: String) {
implementation?.registerDeviceToken(deviceToken)
}
/**
Delete the currently registered device token
*/
public func deleteDeviceToken() {
implementation?.deleteDeviceToken()
}
/**
Track a push metric
*/
public func trackMetric(
deliveryID: String,
event: Metric,
deviceToken: String
) {
implementation?.trackMetric(deliveryID: deliveryID, event: event, deviceToken: deviceToken)
}
} // swiftlint:disable:this file_length