Fighting against KMP and Firebase Analytics

A small guide that I hope can be useful for understanding how to integrate Firebase Analytics into a Kotlin Multiplatform (KMP) project, without using Cocoapods on the iOS side.

This is a standard approach that can be used for any need where you have to use native iOS libraries.

First of all, avoid using Cocoapods in every way, both in the KMP project and in the iOS project.

Practical Example

  • Initial Setup: The Firebase Analytics library is imported as a Gradle dependency on the Android side, and as an SPM (Swift Package Manager) dependency on the iOS side.
  • Create an expect interface, for example:
    expect interface AnalyticsService {
        fun logEvent(name: String, params: Map<String, Any>?)
    }
  • Create the two actual interfaces, one for Android and one for iOS, defined in Kotlin (in their respective source sets):
    // in androidMain
    actual interface AnalyticsService { 
        actual fun logEvent(name: String, params: Map<String, Any>?) 
    }
    
    // in iosMain
    actual interface AnalyticsService { 
        actual fun logEvent(name: String, params: Map<String, Any>?) 
    }
  • Create a Kotlin implementation for Android of the Android actual interface, which uses the Gradle dependency.
  • Create a Swift implementation for iOS of the iOS actual interface, which uses the SPM dependency. Here’s a very simplified example of how to expose Swift logic to the KMP module:
    import FirebaseAnalytics // The SPM dependency
    
    @main
    class iOSAnalyticsService: AnalyticsService { // The class exposed to Kotlin
        func logEvent(name: String, params: [String : Any]?) {
            Analytics.logEvent(name, parameters: params)
        }
    }

That’s all it takes.

WTF…so simple…I banged my head against the wall for weeks….

Can it perhaps be optimized? Certainly, but as a first step, this works perfectly fine. If I find improvements, I’ll write another couple of lines here.


Lessons Learned

  • Cocoapods is awful
  • Asking these things to AIs like ChatGPT or Gemini is a waste of time; they just guess like a kid. Embarrassing.
  • Getting into the KMP mindset is truly complicated.
 

sarbyn

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.