-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathReactIterableAPI.swift
691 lines (530 loc) · 24 KB
/
ReactIterableAPI.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//
// Created by Tapash Majumder on 3/19/20.
// Copyright © 2020 Iterable. All rights reserved.
//
import Foundation
import IterableSDK
@objc(ReactIterableAPI)
class ReactIterableAPI: RCTEventEmitter {
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - React Native Functions
@objc static override func moduleName() -> String! {
return "RNIterableAPI"
}
override var methodQueue: DispatchQueue! {
_methodQueue
}
@objc override static func requiresMainQueueSetup() -> Bool {
false
}
enum EventName: String, CaseIterable {
case handleUrlCalled
case handleCustomActionCalled
case handleInAppCalled
case handleAuthCalled
case receivedIterableInboxChanged
case handleAuthSuccessCalled
case handleAuthFailureCalled
}
override func supportedEvents() -> [String]! {
var result = [String]()
EventName.allCases.forEach {
result.append($0.rawValue)
}
return result
}
override func startObserving() {
ITBInfo()
shouldEmit = true
}
override func stopObserving() {
ITBInfo()
shouldEmit = false
}
// MARK: - Native SDK Functions
@objc(initializeWithApiKey:config:version:resolver:rejecter:)
func initialize(apiKey: String,
config configDict: [AnyHashable: Any],
version: String,
resolver: @escaping RCTPromiseResolveBlock,
rejecter: @escaping RCTPromiseRejectBlock) {
ITBInfo()
initialize(withApiKey: apiKey,
config: configDict,
version: version,
resolver: resolver,
rejecter: rejecter)
}
@objc(initialize2WithApiKey:config:apiEndPointOverride:version:resolver:rejecter:)
func initialize2(apiKey: String,
config configDict: [AnyHashable: Any],
version: String,
apiEndPointOverride: String,
resolver: @escaping RCTPromiseResolveBlock,
rejecter: @escaping RCTPromiseRejectBlock) {
ITBInfo()
initialize(withApiKey: apiKey,
config: configDict,
version: version,
apiEndPointOverride: apiEndPointOverride,
resolver: resolver,
rejecter: rejecter)
}
@objc(setEmail:)
func set(email: String?) {
ITBInfo()
IterableAPI.email = email
}
@objc(setEmail:authToken:)
func set(email: String?, authToken: String?) {
ITBInfo()
IterableAPI.setEmail(email, authToken)
}
@objc(getEmail:rejecter:)
func getEmail(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.email)
}
@objc(setUserId:)
func set(userId: String?) {
ITBInfo()
IterableAPI.userId = userId
}
@objc(setUserId:authToken:)
func set(userId: String?, authToken: String?) {
ITBInfo()
IterableAPI.setUserId(userId, authToken)
}
@objc(getUserId:rejecter:)
func getUserId(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.userId)
}
// MARK: - Iterable API Request Functions
@objc(setInAppShowResponse:)
func set(inAppShowResponse number: NSNumber) {
ITBInfo()
self.inAppShowResponse = InAppShowResponse.from(number: number)
inAppHandlerSemaphore.signal()
}
@objc(disableDeviceForCurrentUser)
func disableDeviceForCurrentUser() {
ITBInfo()
IterableAPI.disableDeviceForCurrentUser()
}
@objc(getLastPushPayload:rejecter:)
func getLastPushPayload(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.lastPushPayload)
}
@objc(getAttributionInfo:rejecter:)
func getAttributionInfo(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.attributionInfo.map(SerializationUtil.encodableToDictionary))
}
@objc(setAttributionInfo:)
func set(attributionInfo dict: [AnyHashable: Any]?) {
ITBInfo()
guard let dict = dict else {
IterableAPI.attributionInfo = nil
return
}
IterableAPI.attributionInfo = SerializationUtil.dictionaryToDecodable(dict: dict)
}
@objc(trackPushOpenWithCampaignId:templateId:messageId:appAlreadyRunning:dataFields:)
func trackPushOpen(campaignId: NSNumber,
templateId: NSNumber?,
messageId: String,
appAlreadyRunning: Bool,
dataFields: [AnyHashable: Any]?) {
ITBInfo()
IterableAPI.track(pushOpen: campaignId,
templateId: templateId,
messageId: messageId,
appAlreadyRunning: appAlreadyRunning,
dataFields: dataFields)
}
@objc(updateCart:)
func updateCart(items: [[AnyHashable: Any]]) {
ITBInfo()
IterableAPI.updateCart(items: items.compactMap(CommerceItem.from(dict:)))
}
@objc(trackPurchase:items:dataFields:)
func trackPurchase(total: NSNumber,
items: [[AnyHashable: Any]],
dataFields: [AnyHashable: Any]?) {
ITBInfo()
IterableAPI.track(purchase: total,
items: items.compactMap(CommerceItem.from(dict:)),
dataFields: dataFields)
}
@objc(trackInAppOpen:location:)
func trackInAppOpen(messageId: String,
location locationNumber: NSNumber) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
IterableAPI.track(inAppOpen: message, location: InAppLocation.from(number: locationNumber))
}
@objc(trackInAppClick:location:clickedUrl:)
func trackInAppClick(messageId: String,
location locationNumber: NSNumber,
clickedUrl: String) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
IterableAPI.track(inAppClick: message, location: InAppLocation.from(number: locationNumber), clickedUrl: clickedUrl)
}
@objc(trackInAppClose:location:source:clickedUrl:)
func trackInAppClose(messageId: String,
location locationNumber: NSNumber,
source sourceNumber: NSNumber,
clickedUrl: String?) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
if let inAppCloseSource = InAppCloseSource.from(number: sourceNumber) {
IterableAPI.track(inAppClose: message,
location: InAppLocation.from(number: locationNumber),
source: inAppCloseSource,
clickedUrl: clickedUrl)
} else {
IterableAPI.track(inAppClose: message,
location: InAppLocation.from(number: locationNumber),
clickedUrl: clickedUrl)
}
}
@objc(inAppConsume:location:source:)
func inAppConsume(messageId: String,
location locationNumber: NSNumber,
source sourceNumber: NSNumber) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
if let inAppDeleteSource = InAppDeleteSource.from(number: sourceNumber) {
IterableAPI.inAppConsume(message: message,
location: InAppLocation.from(number: locationNumber),
source: inAppDeleteSource)
} else {
IterableAPI.inAppConsume(message: message,
location: InAppLocation.from(number: locationNumber))
}
}
@objc(getHtmlInAppContentForMessage:resolver:rejecter:)
func getHtmlInAppContent(messageId: String, resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
rejecter("", "Could not find message with id: \(messageId)", nil)
return
}
guard let content = message.content as? IterableHtmlInAppContent else {
ITBError("Could not parse message content as HTML")
rejecter("", "Could not parse message content as HTML", nil)
return
}
resolver(content.toDict())
}
@objc(trackEvent:dataFields:)
func trackEvent(name: String, dataFields: [AnyHashable: Any]?) {
ITBInfo()
IterableAPI.track(event: name, dataFields: dataFields)
}
@objc(updateUser:mergeNestedObjects:)
func updateUser(dataFields: [AnyHashable: Any], mergeNestedObjects: Bool) {
ITBInfo()
IterableAPI.updateUser(dataFields, mergeNestedObjects: mergeNestedObjects)
}
@objc(updateEmail:authToken:)
func updateEmail(email: String, with authToken: String?) {
ITBInfo()
if let authToken = authToken {
IterableAPI.updateEmail(email, withToken: authToken, onSuccess: nil, onFailure: nil)
} else {
IterableAPI.updateEmail(email, onSuccess: nil, onFailure: nil)
}
}
@objc(handleAppLink:resolver:rejecter:)
func handle(appLink: String, resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
if let url = URL(string: appLink) {
resolver(IterableAPI.handle(universalLink: url))
} else {
rejecter("", "invalid URL", nil)
}
}
// MARK: - SDK In-App Manager Functions
@objc(getInAppMessages:rejecter:)
func getInAppMessages(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.inAppManager.getMessages().map { $0.toDict() })
}
@objc(getInboxMessages:rejecter:)
func getInboxMessages(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.inAppManager.getInboxMessages().map{ $0.toDict() })
}
@objc(getUnreadInboxMessagesCount:rejecter:)
func getUnreadInboxMessagesCount(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.inAppManager.getUnreadInboxMessagesCount())
}
@objc(showMessage:consume:resolver:rejecter:)
func show(messageId: String, consume: Bool, resolver: @escaping RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
IterableAPI.inAppManager.show(message: message, consume: consume) { (url) in
resolver(url.map({$0.absoluteString}))
}
}
@objc(removeMessage:location:source:)
func remove(messageId: String, location locationNumber: NSNumber, source sourceNumber: NSNumber) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
if let inAppDeleteSource = InAppDeleteSource.from(number: sourceNumber) {
IterableAPI.inAppManager.remove(message: message,
location: InAppLocation.from(number: locationNumber),
source: inAppDeleteSource)
} else {
IterableAPI.inAppManager.remove(message: message,
location: InAppLocation.from(number: locationNumber))
}
}
@objc(updateSubscriptions:unsubscribedChannelIds:unsubscribedMessageTypeIds:subscribedMessageTypeIds:campaignId:templateId:)
func updateSubscriptions(emailListIds: [NSNumber]?,
unsubscribedChannelIds: [NSNumber]?,
unsubscribedMessageTypeIds: [NSNumber]?,
subscribedMessageTypeIds: [NSNumber]?,
campaignId: NSNumber,
templateId: NSNumber) {
ITBInfo()
let finalCampaignId: NSNumber? = campaignId.intValue <= 0 ? nil : campaignId
let finalTemplateId: NSNumber? = templateId.intValue <= 0 ? nil : templateId
IterableAPI.updateSubscriptions(emailListIds,
unsubscribedChannelIds: unsubscribedChannelIds,
unsubscribedMessageTypeIds: unsubscribedMessageTypeIds,
subscribedMessageTypeIds: subscribedMessageTypeIds,
campaignId: finalCampaignId,
templateId: finalTemplateId)
}
@objc(setReadForMessage:read:)
func setRead(for messageId: String, read: Bool) {
ITBInfo()
guard let message = IterableAPI.inAppManager.getMessage(withId: messageId) else {
ITBError("Could not find message with id: \(messageId)")
return
}
IterableAPI.inAppManager.set(read: read, forMessage: message)
}
@objc(setAutoDisplayPaused:)
func set(autoDisplayPaused: Bool) {
ITBInfo()
DispatchQueue.main.async {
IterableAPI.inAppManager.isAutoDisplayPaused = autoDisplayPaused
}
}
// MARK: - SDK Inbox Session Tracking Functions
@objc(startSession:)
func startSession(visibleRows: [[AnyHashable: Any]]) {
let serializedRows = InboxImpressionTracker.RowInfo.rowInfos(from: visibleRows)
inboxSessionManager.startSession(visibleRows: serializedRows)
}
@objc(endSession)
func endSession() {
guard let sessionInfo = inboxSessionManager.endSession() else {
ITBError("Could not find session info")
return
}
let inboxSession = IterableInboxSession(id: sessionInfo.startInfo.id,
sessionStartTime: sessionInfo.startInfo.startTime,
sessionEndTime: Date(),
startTotalMessageCount: sessionInfo.startInfo.totalMessageCount,
startUnreadMessageCount: sessionInfo.startInfo.unreadMessageCount,
endTotalMessageCount: IterableAPI.inAppManager.getInboxMessages().count,
endUnreadMessageCount: IterableAPI.inAppManager.getUnreadInboxMessagesCount(),
impressions: sessionInfo.impressions.map { $0.toIterableInboxImpression() })
IterableAPI.track(inboxSession: inboxSession)
}
@objc(updateVisibleRows:)
func updateVisibleRows(visibleRows: [[AnyHashable: Any]]) {
let serializedRows = InboxImpressionTracker.RowInfo.rowInfos(from: visibleRows)
inboxSessionManager.updateVisibleRows(visibleRows: serializedRows)
}
// MARK: - SDK Auth Manager Functions
@objc(passAlongAuthToken:)
func passAlong(authToken: String?) {
ITBInfo()
passedAuthToken = authToken
authHandlerSemaphore.signal()
}
// MARK: Private
private var shouldEmit = false
private let _methodQueue = DispatchQueue(label: String(describing: ReactIterableAPI.self))
// Handling in-app delegate
private var inAppShowResponse = InAppShowResponse.show
private var inAppHandlerSemaphore = DispatchSemaphore(value: 0)
private var passedAuthToken: String?
private var authHandlerSemaphore = DispatchSemaphore(value: 0)
private let inboxSessionManager = InboxSessionManager()
private func initialize(withApiKey apiKey: String,
config configDict: [AnyHashable: Any],
version: String,
apiEndPointOverride: String? = nil,
resolver: @escaping RCTPromiseResolveBlock,
rejecter: @escaping RCTPromiseRejectBlock) {
ITBInfo()
let launchOptions = createLaunchOptions()
let iterableConfig = IterableConfig.from(dict: configDict)
if let urlHandlerPresent = configDict["urlHandlerPresent"] as? Bool, urlHandlerPresent == true {
iterableConfig.urlDelegate = self
}
if let customActionHandlerPresent = configDict["customActionHandlerPresent"] as? Bool, customActionHandlerPresent == true {
iterableConfig.customActionDelegate = self
}
if let inAppHandlerPresent = configDict["inAppHandlerPresent"] as? Bool, inAppHandlerPresent == true {
iterableConfig.inAppDelegate = self
}
if let authHandlerPresent = configDict["authHandlerPresent"] as? Bool, authHandlerPresent {
iterableConfig.authDelegate = self
}
// connect new inbox in-app payloads to the RN SDK
NotificationCenter.default.addObserver(self, selector: #selector(receivedIterableInboxChanged), name: Notification.Name.iterableInboxChanged, object: nil)
DispatchQueue.main.async {
IterableAPI.initialize2(apiKey: apiKey,
launchOptions: launchOptions,
config: iterableConfig,
apiEndPointOverride: apiEndPointOverride) { result in
resolver(result)
}
IterableAPI.setDeviceAttribute(name: "reactNativeSDKVersion", value: version)
}
}
@objc(receivedIterableInboxChanged)
private func receivedIterableInboxChanged() {
guard shouldEmit else {
return
}
sendEvent(withName: EventName.receivedIterableInboxChanged.rawValue, body: nil)
}
private func createLaunchOptions() -> [UIApplication.LaunchOptionsKey: Any]? {
guard let bridge = bridge else {
return nil
}
return ReactIterableAPI.createLaunchOptions(bridgeLaunchOptions: bridge.launchOptions)
}
private static func createLaunchOptions(bridgeLaunchOptions: [AnyHashable: Any]?) -> [UIApplication.LaunchOptionsKey: Any]? {
guard let bridgeLaunchOptions = bridgeLaunchOptions,
let remoteNotification = bridgeLaunchOptions[UIApplication.LaunchOptionsKey.remoteNotification.rawValue] else {
return nil
}
var result = [UIApplication.LaunchOptionsKey: Any]()
result[UIApplication.LaunchOptionsKey.remoteNotification] = remoteNotification
return result
}
}
extension ReactIterableAPI: IterableURLDelegate {
func handle(iterableURL url: URL, inContext context: IterableActionContext) -> Bool {
ITBInfo()
guard shouldEmit else {
return false
}
let contextDict = ReactIterableAPI.contextToDictionary(context: context)
sendEvent(withName: EventName.handleUrlCalled.rawValue,
body: ["url": url.absoluteString,
"context": contextDict] as [String : Any])
return true
}
private static func contextToDictionary(context: IterableActionContext) -> [AnyHashable: Any] {
var result = [AnyHashable: Any]()
let actionDict = actionToDictionary(action: context.action)
result["action"] = actionDict
result["source"] = context.source.rawValue
return result
}
private static func actionToDictionary(action: IterableAction) -> [AnyHashable: Any] {
var actionDict = [AnyHashable: Any]()
actionDict["type"] = action.type
if let data = action.data {
actionDict["data"] = data
}
if let userInput = action.userInput {
actionDict["userInput"] = userInput
}
return actionDict
}
}
extension ReactIterableAPI: IterableCustomActionDelegate {
func handle(iterableCustomAction action: IterableAction, inContext context: IterableActionContext) -> Bool {
ITBInfo()
let actionDict = ReactIterableAPI.actionToDictionary(action: action)
let contextDict = ReactIterableAPI.contextToDictionary(context: context)
sendEvent(withName: EventName.handleCustomActionCalled.rawValue,
body: ["action": actionDict,
"context": contextDict])
return true
}
}
extension ReactIterableAPI: IterableInAppDelegate {
func onNew(message: IterableInAppMessage) -> InAppShowResponse {
ITBInfo()
guard shouldEmit else {
return .show
}
sendEvent(withName: EventName.handleInAppCalled.rawValue,
body: message.toDict())
let timeoutResult = inAppHandlerSemaphore.wait(timeout: .now() + 2.0)
if timeoutResult == .success {
ITBInfo("inAppShowResponse: \(inAppShowResponse == .show)")
return inAppShowResponse
} else {
ITBInfo("timed out")
return .show
}
}
}
extension ReactIterableAPI: IterableAuthDelegate {
func onAuthTokenRequested(completion: @escaping AuthTokenRetrievalHandler) {
ITBInfo()
DispatchQueue.global(qos: .userInitiated).async {
self.sendEvent(withName: EventName.handleAuthCalled.rawValue,
body: nil)
let authTokenRetrievalResult = self.authHandlerSemaphore.wait(timeout: .now() + 30.0)
if authTokenRetrievalResult == .success {
ITBInfo("authTokenRetrieval successful")
DispatchQueue.main.async {
completion(self.passedAuthToken)
}
self.sendEvent(withName: EventName.handleAuthSuccessCalled.rawValue,
body: nil)
} else {
ITBInfo("authTokenRetrieval timed out")
DispatchQueue.main.async {
completion(nil)
}
self.sendEvent(withName: EventName.handleAuthFailureCalled.rawValue,
body: nil)
}
}
}
func onAuthFailure(_ authFailure: IterableSDK.AuthFailure) {
}
// Deprecated in iterable-swift-sdk 6.5.5: https://github.com/Iterable/iterable-swift-sdk/releases/tag/6.5.5
func onTokenRegistrationFailed(_ reason: String?) {
}
}