Hi can any one help me out in better way of doing ...
# multiplatform
a
Hi can any one help me out in better way of doing this code delegation? Purpose : Log Analytics Events Problem: by this below way i can bypass some of the non supported sdk's of (iOS kotlin) which is only available on swift side common
Copy code
expect object AnalyticsManager {
    fun logEvent(eventType: String, params: Map<String, Any>? = null)
}
iOS (Kotlin)
Copy code
actual object AnalyticsManager {
// posting notification's of events with information about the data that needs to be delegated to swift 

    actual fun logEvent(
        eventType: String,
        params: Map<String, Any>?
    ) {
        val notificationCenter = NSNotificationCenter.defaultCenter
        val userInfo = params?.mapKeys { it.key as Any? }?.mapValues { it.value }
        val notification = NSNotification(eventType, null, userInfo)
        notificationCenter.postNotification(notification)
    }
}
iOS(Swift)
Copy code
func analyticsListener(){
// listening to sender notification's of kotlin code and executing code block in swift
        NotificationCenter.default.addObserver(self, selector: #selector(self.logAnalytics(_:)), name: NSNotification.Name(rawValue: "LOGIN_SUCCESS_EVENT"), object: nil)

    }
    
    @objc func logAnalytics(_ notification: NSNotification) {
        let data = notification.userInfo?.compactMapValues { value -> Any? in
            guard let key = value as? String else { return nil }
            return key
        }
        Analytics.logEvent("LOGIN_SUCCESS_EVENT", parameters: data as? [String: Any])
    }
s
fwiw- I found a relatively simple (read: hacky) way that's been effective: Use a plain
:shared
Kotlin Interface without actual/expect, instantiate the object in iOS using the Interface signature, then pass the object directly back to Kotlin by like an
initWithNativeComponents(iosAnalyticsManager)
that's called before a shared
App.main()
in Kotlin is called (or wherever your entry point is). Something like this: Kotlin:
interface AnalyticsManager {
fun logEvent(eventType: String, params: Map<String, Any>? = null)
}
class AnalyticsManagerImplAndroid : AnalyticsManager {
override fun logEvent(eventType: String, params: Map<String, Any>?) {
// log event
}
}
iOS/Swift::
class AnalyticsManagerImpliOS:AnalyticsManager {
func logEvent(eventType: String, params: [String : Any]?) {
print(params)
}
}
let iosAnalyticsManager = AnalyticsManagerImpliOS()
SharedKotlinApp().instance().initWithNativeComponente(analyticsManager:iosAnalyticsManager)
then
SharedKotlinApp().instance().main()
(to start shared app) It's not the most practical in terms of scalable dependency injection but might could get you further along
a
@steve h this seems pretty simple would try this 🙂 thanks for sharing