LoginSignup
2
0

More than 3 years have passed since last update.

Kotlin Multiplatform Mobile を使ってiOS・Androidの処理を共通化する

Posted at

はじめに

Kotlin Multiplatform Mobile がアルファ段階に移行 – Kotlin Blog | JetBrains ということなので、触ってみます

インストール

[Preferences] -> [Plugins] -> Kotlin Multiplatform Mobile で検索

Kotlin Multiplatform Mobile の作成

Create your first multiplatform application—Kotlin Multiplatform Mobile Docs を参考にすすめます。

  1. New Project から KMM Application を選択して各種Project名を作成
  2. androidApp、iOSAppのビルド設定をする(iOS simulatorを使うためにはXcodeのインストールが必要なので注意


プロジェクトを開くといくつかのサンプルコードが用意されています。
iOSでビルドすると、shared/build/xcode-frameworksにshared.frameworkが生成されます。(Run Scriptで./gradlew :shared:packForXCodeが実行されている)

Greeting.kt
class Greeting {
    fun greeting(): String {
        return "Guess what it is! > ${Platform().platform.reversed()}!"
    }
}
commonMain/.../Platform.kt
expect class Platform() {
    val platform: String
}
androidMain/.../Platform.kt
package com.example.kmmapplication.shared

actual class Platform actual constructor() {
    actual val platform: String = "Android ${android.os.Build.VERSION.SDK_INT}"
}
iOSMain/.../Platform.kt
import platform.UIKit.UIDevice

actual class Platform actual constructor() {
    actual val platform: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}

外部のプロジェクトからの参照する

Kotlin Multiplatform Mobileを作成すると同時にAndroid・iOSプロジェクトが作成されるがここでは、別のプロジェクトから使用してみます。
適当に以下のようにプロジェクトを作成します

KMM
 ├ KMMIos
 ├ KMMAndroid
 └ KMMApplication

iOSプロジェクトから参照する

KMM内のiOSプロジェクトではなく、別のiOSプロジェクトからKMMのコードを使用する方法です。
iOSプロジェクトからはフレームワーク経由での参照になります。普通のフレームワーク同様リンクすれば使用できます。(Framework Search Pathsの設定も忘れずに)
その際、iOSのプロジェクトにも、RunScriptにもFrameworkを生成するgradleの処理をいれておくと最新のモジュールを取得できるので追加しておきます。

これで使えるようになります。

ContentView.swift
import shared

struct ContentView: View {
    var body: some View {
        Text(Greeting().greeting())
    }
}

Androidプロジェクトから参照する

KMM内のAndroidプロジェクトではなく、別のAndroidプロジェクトからKMMのコードを使用する方法です。
Androidプロジェクトからは、gradle経由で参照します。

settings.gradle
include ':app', ':shared'
project(':shared').projectDir = new File(settingsDir, '../KMMApplication/shared')
build.gradle
dependencies {
  implementation project(':shared')
}

これで使えるようになります。

MainActivity.kt
import com.example.kmmapplication.shared.Greeting

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val tv: TextView = findViewById(R.id.text_view)
    tv.text = Greeting().greeting()
  }
}
2
0
0

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
2
0