Find application version code in Kotlin Multiplatform Moblie

2k views Asked by At

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

2

There are 2 answers

5
Phil Dukhov On BEST ANSWER

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
1
Róbert Nagy On

I would only use expect/actual if you want the shared module/framework version.

If you're building a KMM app, however, I'd suspect that the version you need is the app version instead, not the shared module's version.

I'd go with an AppConfig interface/protocol, something like:

interface AppConfig {
    val version: String
}

Then provide the IosAppConfig and AndroidAppConfig implementations from your androidApp and iosApp.