Search code examples
kotlinkotlin-multiplatformkotlin-multiplatform-mobile

Find application version code in Kotlin Multiplatform Moblie


I want to find application version code in Kmm. In specific platform i.e.

Android

var versionCode = BuildConfig.VERSION_CODE

it will return 1.1

iOS

let appVersion = "iOS " + (Bundle.main.versionNumber ?? "")

it will return 1.1

How can I do in Kmm in specific platform?

UPDATE

I tried expect/actual but I am getting some error.

CommonMain

expect class Platform() {
    val versionCode: String
}

iosMain

actual class Platform actual constructor() {
    actual val versionCode =
        platform.Foundation.NSBundle.mainBundle.infoDictionary?.get("CFBundleVersion")
}

Error on iOS side

enter image description here

androidMain

actual class Platform actual constructor() {
    actual val versionCode = BuildConfig.VERSION_CODE
}

Error on android side

enter image description here


Solution

  • KMM doesn't have some built in support for such feature.

    One option is to create an expect function and apply platform-specific code in actual for each platform.

    I used to sync app version with module version, but if you can't do that, you can create Platform in your app module and pass it to your common module:

    Common main:

    expect class Platform { // remove constructor here
        val versionCode: String
    }
    

    Android main:

    actual class Platform(actual val versionCode: String)
    

    Then in app module you just create it Platform(BuildConfig.VERSION_CODE.toString()) and pass it into your shared module depending on your architecture.


    Another option is to use BuildKonfig plugin: it will generate a configuration file like the Android plugin does, depending on what you specify in the build.gradle file:

    buildkonfig {
        packageName = "com.example.app"
    
        defaultConfigs {
            buildConfigField(STRING, "VERSION_CODE", "1.0")
        }
    }
    

    Usage:

    com.example.app.BuildKonfig.VERSION_CODE