11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlin Multiplatform(Android/iOS)でビルド環境ごとに対応した値を利用したい

Last updated at Posted at 2025-06-05

やりたいこと

Debug/Releaseのビルドで環境に対応したAPIのURL等を用意したい。

やり方

  1. Android・iOS、それぞれの環境でビルド時の設定値を用意する
  2. expect/actualで参照する

サンプル:環境に対応したAPIのURLを用意する手順

1. Androidでビルド時の設定値を用意

gradleでdebug/release環境それぞれのAPIのベースとなるURLを用意します。
こうすることでSync nowするとyour-app/BuildConfig.javaが作成され、BuildConfig.API_BASE_URLとすると設定値を読み出すことができます。

build.gradle.kts
buildTypes {
    getByName("debug") {
        buildConfigField("String", "API_BASE_URL", "\"http://10.0.2.2:4001\"")
    }
    getByName("release") {
        isMinifyEnabled = false
        buildConfigField("String", "API_BASE_URL", "\"https://example.com\"")
    }
}

2. iOSでビルド時の設定値を用意

デフォルトでInfo.plistファイルがあるのですがこれをDebug用とRelease用に分けます。

iosApp/iosApp/Info-Debug.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    ....
    <key>API_BASE_URL</key>
    <string>http://localhost:4001</string>
</dict>
</plist>
iosApp/iosApp/Info-Release.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    ....
    <key>API_BASE_URL</key>
    <string>https://example.com</string>
</dict>
</plist>

xcodeでプロジェクトを開き、Debug/Releaseビルド時に上記で指定したファイルを参照するように設定

  1. 左側の階層からiosAppをクリック
  2. Build Settings > TARGETS > iosApp > Packaging > Info.plist File
  3. 以下に変更
    • Debug:iosApp/Info-Debug.plist
    • Release:iosApp/Info-Release.plist
      image.png

3. expect/actualを実装

kotlin/your-app/common/Config.kt
expect object Config {
    val apiBaseUrl: String
}
kotlin/your-app/common/Config.android.kt
import jp.d_publishing.directbooks.BuildConfig

actual object Config {
    actual val apiBaseUrl: String
        get() = BuildConfig.API_BASE_URL
}
kotlin/your-app/common/Config.ios.kt
import platform.Foundation.NSBundle

actual object Config {
    actual val apiBaseUrl: String
        get() =
            NSBundle.mainBundle
                .infoDictionary
                ?.get("API_BASE_URL") as? String
                ?: error("API_BASE_URL not found in Info.plist")
}

終わりに

スマホアプリ開発初心者の私にとって「環境ファイル的なものを一つ用意するだけでどのプラットフォームでもいい感じに動くものでしょ」と思っていましたがそんなことはなかったです。もし知っている方がいらっしゃればコメントをお願いします。同じような感覚のスマホアプリ開発初心者にとってこの記事の内容が参考になれば幸いです。

11
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?