Skip to content

Commit

Permalink
[ios] Refactor event handling and add new event listener
Browse files Browse the repository at this point in the history
  • Loading branch information
RyosukeCla committed Mar 25, 2024
1 parent c051878 commit a383a39
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions ios/Nativebrik/Nativebrik/sdk.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ func openLink(_ event: ComponentEvent) -> Void {
guard let link = event.deepLink else {
return
}
let url = URL(string: link)!
guard let url = URL(string: link) else {
return
}
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:])
Expand All @@ -32,12 +34,23 @@ func openLink(_ event: ComponentEvent) -> Void {
}
}

func createDispatchNativebrikEvent(_ client: NativebrikClient) -> (_ event: ComponentEvent) -> Void {
return { event in
guard let name = event.name else {
return
}
if name.isEmpty {
return
}
client.experiment.dispatch(NativebrikEvent(name))
}
}

class Config {
let projectId: String
var url: String = "https://nativebrik.com/client"
var trackUrl: String = "https://track.nativebrik.com/track/v1"
var cdnUrl: String = "https://cdn.nativebrik.com"
static let defaultListeners: [((_ event: ComponentEvent) -> Void)] = [openLink]
var eventListeners: [((_ event: ComponentEvent) -> Void)] = []

init() {
Expand All @@ -46,22 +59,25 @@ class Config {

init(
projectId: String,
onEvent: ((_ event: ComponentEvent) -> Void)? = nil
onEvents: [((_ event: ComponentEvent) -> Void)?] = []
) {
self.projectId = projectId
if let onEvent = onEvent {
self.eventListeners.append(onEvent)
onEvents.forEach { onEvent in
if let onEvent = onEvent {
self.eventListeners.append(onEvent)
}
}
}

func addEventListner(_ onEvent: @escaping (_ event: ComponentEvent) -> Void) {
self.eventListeners.append(onEvent)
}

func dispatchUIBlockEvent(event: UIBlockEventDispatcher) {
let e = convertEvent(event)
for listener in eventListeners {
listener(e)
}
for listener in Config.defaultListeners {
listener(e)
}
}
}

Expand Down Expand Up @@ -106,7 +122,10 @@ public class NativebrikClient: ObservableObject {
httpRequestInterceptor: NativebrikHttpRequestInterceptor? = nil
) {
let user = NativebrikUser()
let config = Config(projectId: projectId, onEvent: onEvent)
let config = Config(projectId: projectId, onEvents: [
openLink,
onEvent
])
let persistentContainer = createNativebrikCoreDataHelper()
self.user = user
self.config = config
Expand All @@ -118,6 +137,8 @@ public class NativebrikClient: ObservableObject {
)
self.overlayVC = OverlayViewController(user: self.user, container: self.container)
self.experiment = NativebrikExperiment(container: self.container, overlay: self.overlayVC)

config.addEventListner(createDispatchNativebrikEvent(self))
}
}

Expand Down

0 comments on commit a383a39

Please sign in to comment.