-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathReactIterableAPI.swift
More file actions
856 lines (754 loc) · 26.2 KB
/
ReactIterableAPI.swift
File metadata and controls
856 lines (754 loc) · 26.2 KB
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
import Foundation
import IterableSDK
import React
@objc public protocol ReactIterableAPIDelegate {
func sendEvent(withName: String, body: Any?)
}
@objc public class ReactIterableAPI: RCTEventEmitter {
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc public weak var delegate: ReactIterableAPIDelegate? = nil
@objc override public class func moduleName() -> String! {
return "RNIterableAPI"
}
override open var methodQueue: DispatchQueue! {
_methodQueue
}
@objc override static public func requiresMainQueueSetup() -> Bool {
false
}
enum EventName: String, CaseIterable {
case handleUrlCalled
case handleCustomActionCalled
case handleInAppCalled
case handleAuthCalled
case receivedIterableInboxChanged
case handleAuthSuccessCalled
case handleAuthFailureCalled
case handleEmbeddedMessageUpdateCalled
case handleEmbeddedMessagingDisabledCalled
case handleTokenRegistrationFailedCalled
}
@objc public static var supportedEvents: [String] {
return EventName.allCases.map(\.rawValue)
}
override public func startObserving() {
ITBInfo()
shouldEmit = true
}
override public func stopObserving() {
ITBInfo()
shouldEmit = false
}
// MARK: - Native SDK Functions
@objc(initializeWithApiKey:config:version:resolver:rejecter:)
public func initializeWithApiKey(
apiKey: String,
config configDict: NSDictionary,
version: String,
resolver: @escaping RCTPromiseResolveBlock,
rejecter: @escaping RCTPromiseRejectBlock
) {
ITBInfo()
initialize(
withApiKey: apiKey,
config: configDict,
version: version,
resolver: resolver,
rejecter: rejecter)
}
@objc(initialize2WithApiKey:config:version:apiEndPointOverride:resolver:rejecter:)
public func initialize2WithApiKey(
apiKey: String,
config configDict: NSDictionary,
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:)
public func setEmail(email: String?) {
ITBInfo()
IterableAPI.email = email
}
@objc(setEmail:authToken:)
public func setEmail(email: String?, authToken: String?) {
ITBInfo()
IterableAPI.setEmail(email, authToken)
}
@objc(getEmail:rejecter:)
public func getEmail(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.email)
}
@objc(setUserId:)
public func setUserId(userId: String?) {
ITBInfo()
IterableAPI.userId = userId
}
@objc(setUserId:authToken:)
public func setUserId(userId: String?, authToken: String?) {
ITBInfo()
IterableAPI.setUserId(userId, authToken)
}
@objc(getUserId:rejecter:)
public func getUserId(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.userId)
}
// MARK: - Iterable API Request Functions
@objc(setInAppShowResponse:)
public func setInAppShowResponse(inAppShowResponse number: Double) {
ITBInfo()
self.inAppShowResponse = InAppShowResponse.from(number: number as NSNumber)
inAppHandlerSemaphore.signal()
}
@objc(disableDeviceForCurrentUser)
public func disableDeviceForCurrentUser() {
ITBInfo()
IterableAPI.disableDeviceForCurrentUser()
}
@objc(getLastPushPayload:rejecter:)
public func getLastPushPayload(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock)
{
ITBInfo()
resolver(IterableAPI.lastPushPayload)
}
@objc(getAttributionInfo:rejecter:)
public func getAttributionInfo(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock)
{
ITBInfo()
resolver(IterableAPI.attributionInfo.map(SerializationUtil.encodableToDictionary))
}
@objc(setAttributionInfo:)
public func setAttributionInfo(attributionInfo dict: NSDictionary?) {
ITBInfo()
guard let swiftDict = dict as? [AnyHashable: Any] else {
IterableAPI.attributionInfo = nil
return
}
IterableAPI.attributionInfo = SerializationUtil.dictionaryToDecodable(
dict: swiftDict)
}
@objc(trackPushOpenWithCampaignId:templateId:messageId:appAlreadyRunning:dataFields:)
public func trackPushOpenWithCampaignId(
campaignId: Double,
templateId: NSNumber?,
messageId: String,
appAlreadyRunning: Bool,
dataFields: NSDictionary?
) {
ITBInfo()
let swiftDict = dataFields as? [AnyHashable: Any]
IterableAPI.track(
pushOpen: campaignId as NSNumber,
templateId: templateId,
messageId: messageId,
appAlreadyRunning: appAlreadyRunning,
dataFields: swiftDict)
}
@objc(updateCart:)
public func updateCart(items: [[AnyHashable: Any]]) {
ITBInfo()
IterableAPI.updateCart(items: items.compactMap(CommerceItem.from(dict:)))
}
@objc(trackPurchase:items:dataFields:)
public func trackPurchase(
total: Double,
items: [[AnyHashable: Any]],
dataFields: [AnyHashable: Any]?
) {
ITBInfo()
IterableAPI.track(
purchase: total as NSNumber,
items: items.compactMap(CommerceItem.from(dict:)),
dataFields: dataFields)
}
@objc(trackInAppOpen:location:)
public func trackInAppOpen(
messageId: String,
location locationNumber: Double
) {
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 as NSNumber))
}
@objc(trackInAppClick:location:clickedUrl:)
public func trackInAppClick(
messageId: String,
location locationNumber: Double,
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 as NSNumber),
clickedUrl: clickedUrl)
}
@objc(trackInAppClose:location:source:clickedUrl:)
public func trackInAppClose(
messageId: String,
location locationNumber: Double,
source sourceNumber: Double,
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 as NSNumber) {
IterableAPI.track(
inAppClose: message,
location: InAppLocation.from(number: locationNumber as NSNumber),
source: inAppCloseSource,
clickedUrl: clickedUrl)
} else {
IterableAPI.track(
inAppClose: message,
location: InAppLocation.from(number: locationNumber as NSNumber),
clickedUrl: clickedUrl)
}
}
@objc(inAppConsume:location:source:)
public func inAppConsume(
messageId: String,
location locationNumber: Double,
source sourceNumber: Double
) {
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 as NSNumber) {
IterableAPI.inAppConsume(
message: message,
location: InAppLocation.from(number: locationNumber as NSNumber),
source: inAppDeleteSource)
} else {
IterableAPI.inAppConsume(
message: message,
location: InAppLocation.from(number: locationNumber as NSNumber))
}
}
@objc(getHtmlInAppContentForMessage:resolver:rejecter:)
public 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)",
NSError(domain: "", code: 0, userInfo: 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", NSError(domain: "", code: 0, userInfo: nil))
return
}
resolver(content.toDict())
}
@objc(trackEvent:dataFields:)
public func trackEvent(name: String, dataFields: NSDictionary?) {
ITBInfo()
IterableAPI.track(event: name, dataFields: dataFields as? [AnyHashable: Any])
}
@objc(updateUser:mergeNestedObjects:)
public func updateUser(dataFields: NSDictionary, mergeNestedObjects: Bool) {
ITBInfo()
guard let fields = dataFields as? [AnyHashable: Any] else {
ITBError("Could not cast dataFields to [AnyHashable: Any]")
return
}
IterableAPI.updateUser(fields, mergeNestedObjects: mergeNestedObjects)
}
@objc(updateEmail:authToken:)
public 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:)
public func handle(
appLink: String, resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock
) {
ITBInfo()
if let url = URL(string: appLink) {
resolver(IterableAPI.handle(universalLink: url))
} else {
rejecter("", "invalid URL", NSError(domain: "", code: 0, userInfo: nil))
}
}
// MARK: - SDK In-App Manager Functions
@objc(getInAppMessages:rejecter:)
public func getInAppMessages(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.inAppManager.getMessages().map { $0.toDict() })
}
@objc(getInboxMessages:rejecter:)
public func getInboxMessages(resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) {
ITBInfo()
resolver(IterableAPI.inAppManager.getInboxMessages().map { $0.toDict() })
}
@objc(getUnreadInboxMessagesCount:rejecter:)
public func getUnreadInboxMessagesCount(
resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock
) {
ITBInfo()
resolver(IterableAPI.inAppManager.getUnreadInboxMessagesCount())
}
@objc(showMessage:consume:resolver:rejecter:)
public func showMessage(
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:)
public func removeMessage(
messageId: String, location locationNumber: Double, source sourceNumber: Double
) {
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 as NSNumber) {
IterableAPI.inAppManager.remove(
message: message,
location: InAppLocation.from(number: locationNumber as NSNumber),
source: inAppDeleteSource)
} else {
IterableAPI.inAppManager.remove(
message: message,
location: InAppLocation.from(number: locationNumber as NSNumber))
}
}
@objc(
updateSubscriptions:unsubscribedChannelIds:unsubscribedMessageTypeIds:subscribedMessageTypeIds:
campaignId:templateId:
)
public func updateSubscriptions(
emailListIds: [NSNumber]?,
unsubscribedChannelIds: [NSNumber]?,
unsubscribedMessageTypeIds: [NSNumber]?,
subscribedMessageTypeIds: [NSNumber]?,
campaignId: Double,
templateId: Double
) {
ITBInfo()
let finalCampaignId: NSNumber? =
(campaignId as NSNumber).intValue <= 0 ? nil : campaignId as NSNumber
let finalTemplateId: NSNumber? =
(templateId as NSNumber).intValue <= 0 ? nil : templateId as NSNumber
IterableAPI.updateSubscriptions(
emailListIds,
unsubscribedChannelIds: unsubscribedChannelIds,
unsubscribedMessageTypeIds: unsubscribedMessageTypeIds,
subscribedMessageTypeIds: subscribedMessageTypeIds,
campaignId: finalCampaignId,
templateId: finalTemplateId,
onSuccess: nil,
onFailure: nil)
}
@objc(setReadForMessage:read:)
public func setReadForMessage(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:)
public func setAutoDisplayPaused(autoDisplayPaused: Bool) {
ITBInfo()
DispatchQueue.main.async {
IterableAPI.inAppManager.isAutoDisplayPaused = autoDisplayPaused
}
}
// MARK: - SDK Inbox Session Tracking Functions
@objc(startSession:)
public func startSession(visibleRows: [[AnyHashable: Any]]) {
let serializedRows = InboxImpressionTracker.RowInfo.rowInfos(from: visibleRows)
inboxSessionManager.startSession(visibleRows: serializedRows)
}
@objc(endSession)
public 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:)
public func updateVisibleRows(visibleRows: [[AnyHashable: Any]]) {
let serializedRows = InboxImpressionTracker.RowInfo.rowInfos(from: visibleRows)
inboxSessionManager.updateVisibleRows(visibleRows: serializedRows)
}
// MARK: - SDK Auth Manager Functions
@objc(passAlongAuthToken:)
public func passAlongAuthToken(authToken: String?) {
ITBInfo()
self.passedAuthToken = authToken
authHandlerSemaphore.signal()
}
@objc(pauseAuthRetries:)
public func pauseAuthRetries(pauseRetry: Bool) {
ITBInfo()
IterableAPI.pauseAuthRetries(pauseRetry)
}
// MARK: - SDK Embedded Messaging Functions
@objc(startEmbeddedSession)
public func startEmbeddedSession() {
ITBInfo()
EmbeddedSessionManager.shared.startSession()
}
@objc(endEmbeddedSession)
public func endEmbeddedSession() {
ITBInfo()
EmbeddedSessionManager.shared.endSession()
}
@objc(syncEmbeddedMessages)
public func syncEmbeddedMessages() {
ITBInfo()
IterableAPI.embeddedManager.syncMessages { }
}
@objc(getEmbeddedMessages:resolver:rejecter:)
public func getEmbeddedMessages(
placementIds: [NSNumber]?, resolver: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock
) {
ITBInfo()
var messages: [IterableEmbeddedMessage] = []
if let placementIds = placementIds, !placementIds.isEmpty {
// Get messages for specific placement IDs
for placementId in placementIds {
let placementMessages = IterableAPI.embeddedManager.getMessages(
for: placementId.intValue
)
messages.append(contentsOf: placementMessages)
}
} else {
// Get all messages from all placements
// getMessages() without parameters flattens all placement messages into a single array
messages = IterableAPI.embeddedManager.getMessages()
}
resolver(messages.map { $0.toDict() })
}
@objc(startEmbeddedImpression:placementId:)
public func startEmbeddedImpression(messageId: String, placementId: Double) {
ITBInfo()
EmbeddedSessionManager.shared.startImpression(messageId: messageId, placementId: placementId)
}
@objc(pauseEmbeddedImpression:)
public func pauseEmbeddedImpression(messageId: String) {
ITBInfo()
EmbeddedSessionManager.shared.pauseImpression(messageId: messageId)
}
@objc(trackEmbeddedClick:buttonId:clickedUrl:)
public func trackEmbeddedClick(
message: NSDictionary, buttonId: String?, clickedUrl: String?
) {
ITBInfo()
// Extract message ID from the dictionary
guard let messageDict = message as? [AnyHashable: Any],
let metadataDict = messageDict["metadata"] as? [AnyHashable: Any],
let messageId = metadataDict["messageId"] as? String else {
ITBError("Could not extract messageId from message dictionary")
return
}
// Find the message in the embedded manager's cache
let messages = IterableAPI.embeddedManager.getMessages()
guard let embeddedMessage = messages.first(where: { $0.metadata.messageId == messageId }) else {
ITBError("Could not find embedded message with id: \(messageId)")
return
}
guard let clickedUrl = clickedUrl else {
ITBError("clickedUrl is required for trackEmbeddedClick")
return
}
IterableAPI.track(
embeddedMessageClick: embeddedMessage,
buttonIdentifier: buttonId,
clickedUrl: clickedUrl
)
}
// 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()
@objc func initialize(
withApiKey apiKey: String,
config configDict: NSDictionary,
version: String,
apiEndPointOverride: String? = nil,
resolver: @escaping RCTPromiseResolveBlock,
rejecter: @escaping RCTPromiseRejectBlock
) {
ITBInfo()
let launchOptions = createLaunchOptions()
guard let configDictTyped = configDict as? [AnyHashable: Any] else {
rejecter("E_INVALID_CONFIG", "configDict could not be cast to [AnyHashable: Any]", nil)
return
}
let iterableConfig = IterableConfig.from(
dict: configDictTyped
)
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 == true
{
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)
// Add embedded update listener if any callback is present
let onEmbeddedMessageUpdatePresent = configDict["onEmbeddedMessageUpdatePresent"] as? Bool ?? false
let onEmbeddedMessagingDisabledPresent = configDict["onEmbeddedMessagingDisabledPresent"] as? Bool ?? false
if onEmbeddedMessageUpdatePresent || onEmbeddedMessagingDisabledPresent {
IterableAPI.embeddedManager.addUpdateListener(self)
}
}
}
@objc(receivedIterableInboxChanged)
func receivedIterableInboxChanged() {
guard shouldEmit else {
return
}
delegate?.sendEvent(
withName: EventName.receivedIterableInboxChanged.rawValue, body: nil as Any?)
}
private func createLaunchOptions() -> [UIApplication.LaunchOptionsKey: Any]? {
guard let bridge = self.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 {
public func handle(iterableURL url: URL, inContext context: IterableActionContext) -> Bool {
ITBInfo()
guard shouldEmit else {
return false
}
let contextDict = ReactIterableAPI.contextToDictionary(context: context)
delegate?.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 {
public func handle(
iterableCustomAction action: IterableAction, inContext context: IterableActionContext
)
-> Bool
{
ITBInfo()
let actionDict = ReactIterableAPI.actionToDictionary(action: action)
let contextDict = ReactIterableAPI.contextToDictionary(context: context)
delegate?.sendEvent(
withName: EventName.handleCustomActionCalled.rawValue,
body: [
"action": actionDict,
"context": contextDict,
])
return true
}
}
extension ReactIterableAPI: IterableInAppDelegate {
public func onNew(message: IterableInAppMessage) -> InAppShowResponse {
ITBInfo()
guard shouldEmit else {
return .show
}
delegate?.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 {
public func onAuthFailure(_ authFailure: IterableSDK.AuthFailure) {
ITBInfo()
var failureDict: [String: Any] = [:]
failureDict["userKey"] = authFailure.userKey
failureDict["failedAuthToken"] = authFailure.failedAuthToken
failureDict["failedRequestTime"] = authFailure.failedRequestTime
failureDict["failureReason"] = authFailure.failureReason.rawValue
delegate?.sendEvent(
withName: EventName.handleAuthFailureCalled.rawValue,
body: failureDict)
}
public func onAuthTokenRequested(completion: @escaping AuthTokenRetrievalHandler) {
ITBInfo()
DispatchQueue.global(qos: .userInitiated).async {
self.delegate?.sendEvent(
withName: EventName.handleAuthCalled.rawValue,
body: nil as Any?)
let authTokenRetrievalResult = self.authHandlerSemaphore.wait(timeout: .now() + 30.0)
if authTokenRetrievalResult == .success {
ITBInfo("authTokenRetrieval successful")
DispatchQueue.main.async {
completion(self.passedAuthToken)
}
self.delegate?.sendEvent(
withName: EventName.handleAuthSuccessCalled.rawValue,
body: nil as Any?)
} else {
ITBInfo("authTokenRetrieval timed out")
DispatchQueue.main.async {
completion(nil)
}
// TODO: RN should be able to handle nil case as well. Or we can wrap this up under one of the existing AuthFailure. But again, its not a authFailure in this one. Its a timeout error.
// TODO: Create a Dictionary representing AuthFailure object due to `null` auth token and pass it in body instead of passing `nil`
self.delegate?.sendEvent(
withName: EventName.handleAuthFailureCalled.rawValue,
body: nil as Any?)
}
}
}
public func onTokenRegistrationFailed(_ reason: String?) {
ITBInfo()
guard shouldEmit else {
return
}
var body: [String: Any] = [:]
if let reason = reason {
body["reason"] = reason
}
delegate?.sendEvent(
withName: EventName.handleTokenRegistrationFailedCalled.rawValue,
body: body)
}
}
extension ReactIterableAPI: IterableEmbeddedUpdateDelegate {
public func onMessagesUpdated() {
ITBInfo()
guard shouldEmit else {
return
}
delegate?.sendEvent(
withName: EventName.handleEmbeddedMessageUpdateCalled.rawValue,
body: nil as Any?)
}
public func onEmbeddedMessagingDisabled() {
ITBInfo()
guard shouldEmit else {
return
}
delegate?.sendEvent(
withName: EventName.handleEmbeddedMessagingDisabledCalled.rawValue,
body: nil as Any?)
}
}