I'm trying to create my first KMM project ( using Ktor to get a simple query ). I've managed to run it in Android, but each time I try in iOS i got an exception when i use Ktor.
This is my gradle
"Shared"
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
id("com.android.library")
id("com.squareup.sqldelight")
}
kotlin {
android()
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64()
).forEach {
it.binaries.framework {
baseName = "shared"
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1")
implementation("io.ktor:ktor-client-core:1.6.6")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.3.2")
implementation("io.ktor:ktor-client-serialization:1.6.5")
implementation("com.squareup.sqldelight:runtime:1.5.3")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
}
}
val androidMain by getting {
dependencies {
implementation("io.ktor:ktor-client-android:1.6.5")
implementation("com.squareup.sqldelight:android-driver:1.5.3")
}
}
val androidTest by getting
val iosX64Main by getting
val iosArm64Main by getting
val iosSimulatorArm64Main by getting
val iosMain by creating {
dependsOn(commonMain)
iosX64Main.dependsOn(this)
iosArm64Main.dependsOn(this)
iosSimulatorArm64Main.dependsOn(this)
dependencies {
implementation("io.ktor:ktor-client-ios:1.6.5")
implementation("com.squareup.sqldelight:native-driver:1.5.3")
}
}
val iosX64Test by getting
val iosArm64Test by getting
val iosSimulatorArm64Test by getting
val iosTest by creating {
dependsOn(commonTest)
iosX64Test.dependsOn(this)
iosArm64Test.dependsOn(this)
iosSimulatorArm64Test.dependsOn(this)
}
}
}
android {
compileSdk = 32
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdk = 21
targetSdk = 32
}
}
sqldelight {
database("AppDatabase") {
packageName = "com.example.basekmm_003"
}
}
This is the base gradle
buildscript {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.21")
classpath("com.android.tools.build:gradle:7.2.0")
classpath("com.squareup.sqldelight:gradle-plugin:1.5.3")
classpath("org.jetbrains.kotlin:kotlin-serialization:1.6.21")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
The Android Studio version I'm using is: Chipmunk / 2021.2.1
The code for my api is:
class JsonApi() {
suspend fun getLatestMovies(): List<JsonMessage>? =
KtorClient.httpClient.get {
url("https://gitcdn.link/cdn/KaterinaPetrova/greeting/7d47a42fc8d28820387ac7f4aaf36d69e434adc1/greetings.json")
}
}
#Serializable
data class JsonMessage(val string: String?, val lang: String?)
object KtorClient {
private val json = Json {
encodeDefaults = true
ignoreUnknownKeys = true
}
val httpClient = HttpClient {
install(JsonFeature) { serializer = KotlinxSerializer(json) }
install(HttpTimeout) {
socketTimeoutMillis = 30_000
requestTimeoutMillis = 30_000
connectTimeoutMillis = 30_000
}
defaultRequest {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
}
}
And the iOS Code is
#main
struct iOSApp: App {
let sdk = MovieSDK(databaseDriverFactory: DatabaseDriverFactory())
var body: some Scene {
WindowGroup {
ContentView(viewModel: .init(sdk: sdk))
}
}
}
struct RocketLaunchRow: View {
var jsonMessage: JsonMessage
var body: some View {
HStack() {
VStack(alignment: .leading, spacing: 10.0) {
Text("Launch name: \(jsonMessage)")
}
Spacer()
}
}
}
struct ContentView: View {
#ObservedObject private(set) var viewModel: ViewModel
enum LoadableLaunches {
case loading
case result([JsonMessage])
case error(String)
}
var body: some View {
NavigationView {
listView()
.navigationBarTitle("SpaceX Launches")
.navigationBarItems(trailing:
Button("Reload") {
self.viewModel.loadLaunches()
}
)
}
}
private func listView() -> AnyView {
switch viewModel.launches {
case .loading:
return AnyView(Text("Loading...").multilineTextAlignment(.center))
case .result(_):
return AnyView(
Text("Succes")
)
case .error(let description):
return AnyView(Text(description).multilineTextAlignment(.center))
}
}
class ViewModel: ObservableObject {
let sdk: MovieSDK
#Published var launches = LoadableLaunches.loading
init(sdk: MovieSDK) {
self.sdk = sdk
self.loadLaunches()
}
func loadLaunches() {
self.launches = .loading
sdk.getLatestMovies(completionHandler: { launches, error in
if let launches = launches {
self.launches = .result(launches)
} else {
self.launches = .error(error?.localizedDescription ?? "error")
}
}
)
}
}
}
The exception I'm getting is:
What I'm doing wrong?, I've tried several approaches with the same result ( event with different urls )
Related
I get this error while building a specific project:
error while writing /home/myuser/AndroidStudioProjects/WalletConnectKotlinV2/foundation/build/classes/kotlin/main/com/walletconnect/foundation/network/model/RelayDTO_Subscribe_Result_AcknowledgementJsonAdapter$annotationImpl$com_walletconnect_foundation_common_adapters_SubscriptionIdAdapter_Qualifier$0.class (Permission denied)
While I ensured chmodding everything properly (yes: ugo+w!!!!!!), I'm still getting the same error. When looking through this link they said this might be related to the file name being too long, and gave what it seems to be something framework-specific to solve it.
This project, in particular, was made by someone else and I just cloned it to try using the related packages (WalletConnect per se is out of the scope of this question, but the project is anyway cloned). I am running the latest Android Studio version (2021.3.1, released few months ago). What can I do to ensure this code actually builds instead of giving me this error?
The gradle file looks like this:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("java-library")
kotlin("jvm")
id("com.google.devtools.ksp") version kspVersion
id("publish-module-java")
}
project.apply {
extra[KEY_PUBLISH_ARTIFACT_ID] = "foundation"
extra[KEY_PUBLISH_VERSION] = "1.2.0-SNAPSHOT"
extra[KEY_SDK_NAME] = "Foundation"
}
java {
sourceCompatibility = jvmVersion
targetCompatibility = jvmVersion
}
tasks.withType<KotlinCompile>() {
kotlinOptions {
jvmTarget = jvmVersion.toString()
}
}
tasks.withType<Test>() {
systemProperty("SDK_VERSION", requireNotNull(project.extra.get(KEY_PUBLISH_VERSION)))
systemProperty("TEST_RELAY_URL", System.getenv("TEST_RELAY_URL"))
systemProperty("TEST_PROJECT_ID", System.getenv("TEST_PROJECT_ID"))
}
dependencies {
scarlet()
okhttp()
koinJvm()
moshi()
moshiKsp()
bouncyCastle()
multibaseJava()
restEasyJava()
jUnit5()
mockk()
}
While these (buildSrc) functions look mostly like this:
// The constants file:
import org.gradle.api.JavaVersion
const val KEY_PUBLISH_VERSION = "PUBLISH_VERSION"
const val KEY_PUBLISH_ARTIFACT_ID = "PUBLISH_ARTIFACT_ID"
const val KEY_SDK_NAME = "SDK_NAME"
const val dokkaVersion = "1.6.21"
const val CORE_VERSION = "1.6.0"
const val BOM_VERSION = "1.0.1"
val jvmVersion = JavaVersion.VERSION_11
const val MIN_SDK: Int = 23
const val TARGET_SDK: Int = 32
const val COMPILE_SDK: Int = TARGET_SDK
const val kotlinVersion = "1.7.10"
const val kspVersion = "1.7.10-1.0.6"
const val sqlDelightVersion = "1.5.2"
const val moshiVersion = "1.13.0"
const val coroutinesVersion = "1.6.4"
const val scarletVersion = "1.0.0"
const val scarletPackage = "com.github.WalletConnect.Scarlet"
const val koinVersion = "3.2.0"
const val mlKitBarcode = "16.0.1"
const val camera2Version = "1.1.0-alpha01"
const val lifecycleVersion = "2.5.1"
const val lifecycleRuntimeKtx = "2.4.1"
const val navVersion = "2.4.1"
const val retrofitVersion = "2.9.0"
const val okhttpVersion = "4.9.0"
const val bouncyCastleVersion = "1.70"
const val sqlCipherVersion = "4.5.0#aar"
const val multibaseVersion = "1.1.0"
const val jUnit5Version = "5.7.2"
const val androidxTestVersion = "1.4.0"
const val robolectricVersion = "4.6"
const val mockkVersion = "1.12.0"
const val jsonVersion = "20220320"
const val timberVersion = "5.0.1"
const val androidSecurityVersion = "1.1.0-alpha03"
const val web3jVersion = "4.9.4"
const val restEasyVersion = "3.15.3.Final"
// The functions file:
import org.gradle.kotlin.dsl.DependencyHandlerScope
fun DependencyHandlerScope.scanner() {
"implementation"("com.google.mlkit:barcode-scanning:$mlKitBarcode")
"implementation"("androidx.camera:camera-camera2:$camera2Version")
"implementation"("androidx.camera:camera-lifecycle:$camera2Version")
"implementation"("androidx.camera:camera-view:1.0.0-alpha21")
}
fun DependencyHandlerScope.lifecycle() {
"implementation"("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion")
"implementation"("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion")
"implementation"("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycleRuntimeKtx")
}
fun DependencyHandlerScope.navigationComponent() {
"api"("androidx.navigation:navigation-fragment-ktx:$navVersion")
"api"("androidx.navigation:navigation-ui-ktx:$navVersion")
}
fun DependencyHandlerScope.coroutines() {
"api"("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion")
}
fun DependencyHandlerScope.coroutinesTest() {
"testImplementation"("org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion")
}
fun DependencyHandlerScope.scarlet() {
"api"("$scarletPackage:scarlet:$scarletVersion")
"api"("$scarletPackage:websocket-okhttp:$scarletVersion")
"api"("$scarletPackage:stream-adapter-coroutines:$scarletVersion")
"api"("$scarletPackage:message-adapter-moshi:$scarletVersion")
}
fun DependencyHandlerScope.scarletAndroid() {
"api"("$scarletPackage:lifecycle-android:$scarletVersion")
}
fun DependencyHandlerScope.scarletTest() {
"testImplementation"("$scarletPackage:websocket-mockwebserver:$scarletVersion")
"testImplementation"("$scarletPackage:test-utils:$scarletVersion")
}
fun DependencyHandlerScope.retrofit() {
"api"("com.squareup.retrofit2:retrofit:$retrofitVersion")
"api"("com.squareup.retrofit2:converter-moshi:$retrofitVersion")
}
fun DependencyHandlerScope.moshi() {
"api"("com.squareup.moshi:moshi-adapters:$moshiVersion")
"api"("com.squareup.moshi:moshi-kotlin:$moshiVersion")
}
fun DependencyHandlerScope.moshiKsp() {
"ksp"("com.squareup.moshi:moshi-kotlin-codegen:$moshiVersion")
}
fun DependencyHandlerScope.okhttp() {
"api"(platform("com.squareup.okhttp3:okhttp-bom:$okhttpVersion"))
"api"("com.squareup.okhttp3:okhttp")
"api"("com.squareup.okhttp3:logging-interceptor")
}
fun DependencyHandlerScope.bouncyCastle() {
"api"("org.bouncycastle:bcprov-jdk15on:$bouncyCastleVersion")
}
fun DependencyHandlerScope.sqlDelightAndroid() {
"api"("com.squareup.sqldelight:android-driver:$sqlDelightVersion")
"api"("com.squareup.sqldelight:coroutines-extensions-jvm:$sqlDelightVersion")
}
fun DependencyHandlerScope.sqlCipher() {
"api"("net.zetetic:android-database-sqlcipher:$sqlCipherVersion")
}
fun DependencyHandlerScope.sqlDelightTest() {
"testImplementation"("com.squareup.sqldelight:sqlite-driver:$sqlDelightVersion")
"testImplementation"("org.xerial:sqlite-jdbc:3.8.10.2") {
// Override the version of sqlite used by sqlite-driver to match Android API 23
version {
strictly("3.8.10.2")
}
}
}
fun DependencyHandlerScope.koinJvm() {
"implementation"("io.insert-koin:koin-core:$koinVersion")
}
fun DependencyHandlerScope.koinAndroid() {
"api"("io.insert-koin:koin-android:$koinVersion")
}
fun DependencyHandlerScope.koinTest() {
"testImplementation"("io.insert-koin:koin-test-junit5:$koinVersion")
}
fun DependencyHandlerScope.glide_N_kapt() {
"implementation"("com.github.bumptech.glide:glide:4.12.0")
"kapt"("com.github.bumptech.glide:compiler:4.12.0")
}
fun DependencyHandlerScope.multibaseJava() {
"api"("com.github.multiformats:java-multibase:$multibaseVersion") //https://mvnrepository.com/artifact/com.github.multiformats/java-multibase/1.1.0 vulnerability detected with library
}
fun DependencyHandlerScope.restEasyJava() {
"implementation"("org.jboss.resteasy:resteasy-jaxrs:$restEasyVersion")
}
fun DependencyHandlerScope.jUnit5() {
"testImplementation"(platform("org.junit:junit-bom:$jUnit5Version"))
"testImplementation"("org.junit.jupiter:junit-jupiter-api:$jUnit5Version")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:$jUnit5Version")
"testImplementation"("org.jetbrains.kotlin:kotlin-test-junit5:$kotlinVersion")
}
fun DependencyHandlerScope.jUnit5Android() {
"androidTestImplementation"("org.junit.jupiter:junit-jupiter-api:$jUnit5Version")
"androidTestImplementation"("de.mannodermaus.junit5:android-test-core:1.3.0")
"androidTestRuntimeOnly"("de.mannodermaus.junit5:android-test-runner:1.3.0")
}
fun DependencyHandlerScope.androidXTest() {
"testImplementation"("androidx.test.ext:junit-ktx:1.1.3")
"testImplementation"("androidx.test:core-ktx:$androidxTestVersion")
"androidTestImplementation"("androidx.test:core-ktx:$androidxTestVersion")
"androidTestImplementation"("androidx.test:runner:$androidxTestVersion")
"androidTestImplementation"("androidx.test:rules:$androidxTestVersion")
}
fun DependencyHandlerScope.robolectric() {
"testImplementation"("org.robolectric:robolectric:$robolectricVersion")
}
fun DependencyHandlerScope.mockk() {
"testImplementation"("io.mockk:mockk:$mockkVersion")
}
fun DependencyHandlerScope.testJson() {
"testImplementation"("org.json:json:$jsonVersion")
}
fun DependencyHandlerScope.timber() {
"api"("com.jakewharton.timber:timber:$timberVersion")
}
fun DependencyHandlerScope.security() {
"api"("androidx.security:security-crypto-ktx:$androidSecurityVersion")
}
fun DependencyHandlerScope.web3jCrypto() {
"api"("org.web3j:crypto:$web3jVersion")
}
I used Moko-socketio library to handle the socket in our multiplatform app but when I run the app, The socket is not connected.
This is logcat error:
error io.socket.engineio.client.EngineIOException: websocket error
error io.socket.client.SocketIOException: Connection error
Note: I used the sample moko-socketio codes for testing.
project build.gradle.kts:
buildscript {
repositories {
gradlePluginPortal()
google()
mavenCentral()
maven {
url = uri("https://plugins.gradle.org/m2/")
}
}
dependencies {
classpath(Build.kotlinGradlePlugin)
classpath(Build.buildTools)
classpath(Build.sqlDelightGradlePlugin)
classpath("dev.icerock:mobile-multiplatform:0.14.2")
}
}
plugins {
//trick: for the same plugin versions in all sub-modules
id(KotlinPlugins.comAndroidApplication).version(KotlinPlugins.version).apply(false)
id(KotlinPlugins.comAndroidLibrary).version(KotlinPlugins.version).apply(false)
id(Plugins.sqlDelight).version(SQLDelight.sqlDelightVersion).apply(false)
id("dev.icerock.mobile.multiplatform.cocoapods").version("0.14.2").apply(false)
kotlin(KotlinPlugins.android).version(Kotlin.version).apply(false)
kotlin(KotlinPlugins.multiplatform).version(Kotlin.version).apply(false)
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
Shared build.gradle.kts:
plugins {
kotlin("native.cocoapods")
kotlin(KotlinPlugins.multiplatform)
id(KotlinPlugins.comAndroidLibrary)
kotlin(KotlinPlugins.serialization) version Kotlin.version
id(Plugins.sqlDelight)
id("dev.icerock.mobile.multiplatform.cocoapods")
id("dev.icerock.mobile.multiplatform.ios-framework")
}
kotlin {
android()
iosX64()
iosArm64()
iosSimulatorArm64()
cocoapods {
summary = "Some description for the Shared Module"
homepage = "Link to the Shared Module homepage"
version = "1.0"
ios.deploymentTarget = "14.1"
podfile = project.file("../iosApp/Podfile")
framework {
baseName = "shared"
}
}
sourceSets {
val commonMain by getting {
dependencies {
with(Koin) {
implementation(koinCore)
implementation(koinTest)
}
with(Coroutines) {
implementation(coreCoroutines)
}
with(Ktor) {
implementation(core)
implementation(ktorClientContentNegotiation)
implementation(ktorSerializationJson)
}
with(SQLDelight) {
implementation(runtime)
}
}
}
val commonTest by getting {
dependencies {
// implementation(kotlin("test"))
}
}
val androidMain by getting {
dependencies {
with(Ktor){
implementation(ktorClientAndroid)
implementation(ktorClientOkhttp)
}
// api(MokoResources.androidMainApi1)
// implementation(SQLDelight.androidDriver)
}
}
val androidTest by getting
val iosX64Main by getting
val iosArm64Main by getting
val iosMain by creating {
dependsOn(commonMain)
iosX64Main.dependsOn(this)
iosArm64Main.dependsOn(this)
}
val iosX64Test by getting
val iosArm64Test by getting
val iosTest by creating {
dependsOn(commonTest)
iosX64Test.dependsOn(this)
iosArm64Test.dependsOn(this)
}
}
}
sqldelight {
database(Database.databaseName) {
packageName = Database.databasePackageName
sourceFolders = listOf(Database.databaseSourceFolder)
}
}
android {
namespace = Application.namespace_
compileSdk = Application.compileSdk
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdk = Application.minSdk
targetSdk = Application.targetSdk
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies {
with(Moko){
commonMainApi(moko)
commonMainApi(serializationJson)
}
}
cocoaPods {
podsProject = file("../ios-app/Pods/Pods.xcodeproj") // here should be path to Pods xcode project
pod("mokoSocketIo", onlyLink = true)
}
Podfile:
target 'iosApp' do
use_frameworks!
platform :ios, '14.1'
pod 'shared', :path => '../shared'
pod 'mokoSocketIo', :git => 'https://github.com/icerockdev/moko-socket-io.git', :tag => 'release/0.3.0'
end
here is my socket class that contains the socket codes:
class Socket {
val socket = Socket(
endpoint = "https://socketio-chat-h9jt.herokuapp.com",
config = SocketOptions(
queryParams = null,
transport = SocketOptions.Transport.WEBSOCKET
)
) {
on(SocketEvent.Connect) {
println("connect")
}
on(SocketEvent.Connecting) {
println("connecting")
}
on(SocketEvent.Disconnect) {
println("disconnect")
}
on(SocketEvent.Error) {
println("error $it")
}
on(SocketEvent.Reconnect) {
println("reconnect")
}
on(SocketEvent.ReconnectAttempt) {
println("reconnect attempt $it")
}
on(SocketEvent.Ping) {
println("ping")
}
on(SocketEvent.Pong) {
println("pong")
}
listOf(
"input",
"login",
"new message",
"user joined",
"user left",
"typing",
"stop typing"
).forEach { eventName ->
on(eventName) { data ->
println("$eventName $data")
}
}
}
fun login() {
socket.emit("add user", "mokoSocketIo")
}
}
here I used the socket class in MainActivity and I want to log the socket connected state but I get false in any run
Socket().apply {
socket.connect()
login()
Log.e("ooo", "${socket.isConnected()}")
}
I am trying to use SQLDelight in a Kotlin Multiplatform project for android and iOS. I have followed the documentation found here. The project builds successfully, but I can't access com.squareup.* anywhere inside the shared/iosMain folder. Below are my code files.
Project/build.gradle.kts:
buildscript {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31")
classpath("com.android.tools.build:gradle:7.0.3")
classpath("com.squareup.sqldelight:gradle-plugin:1.5.2")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
Project/shared/build.gradle.kts:
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
kotlin("native.cocoapods")
id("com.android.library")
id("com.squareup.sqldelight")
}
version = "1.0"
kotlin {
android()
val iosTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget = when {
System.getenv("SDK_NAME")?.startsWith("iphoneos") == true -> ::iosArm64
System.getenv("NATIVE_ARCH")?.startsWith("arm") == true -> ::iosSimulatorArm64
else -> ::iosX64
}
iosTarget("ios") {}
cocoapods {
summary = "Some description for the Shared Module"
homepage = "Link to the Shared Module homepage"
ios.deploymentTarget = "14.1"
frameworkName = "shared"
podfile = project.file("../iosApp/Podfile")
}
sourceSets {
val commonMain by getting {
dependencies {
// SQLDelight
implementation("com.squareup.sqldelight:runtime:1.5.2")
implementation ("com.squareup.sqldelight:coroutines-extensions:1.5.0")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val androidMain by getting {
dependencies {
implementation("com.squareup.sqldelight:android-driver:1.5.0")
}
}
val androidTest by getting {
dependencies {
implementation(kotlin("test-junit"))
implementation("junit:junit:4.13.2")
}
}
val iosMain by getting {
dependencies {
implementation("com.squareup.sqldelight:native-driver:1.5.2")
}
}
val iosTest by getting
}
}
sqldelight {
database("AppDatabase") {
packageName = "com.example.sam.data.db"
dialect = "sqlite:3.25"
}
}
android {
compileSdkVersion(31)
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdkVersion(21)
targetSdkVersion(31)
}
}
Project/shared/src/commonMain/kotlin/com/example/sam/data/db/DatabaseDriverFactory.kt
package com.example.sam.data.db
import com.squareup.sqldelight.db.SqlDriver
expect class DatabaseDriverFactory {
fun createDriver(): SqlDriver
}
Project/shared/src/androidMain/kotlin/com/example/sam/data/db/DatabaseDriverFactory.kt
package com.example.sam.data.db
import android.content.Context
import com.squareup.sqldelight.android.AndroidSqliteDriver
import com.squareup.sqldelight.db.SqlDriver
actual class DatabaseDriverFactory(
private val ctx: Context
) {
actual fun createDriver(): SqlDriver {
return AndroidSqliteDriver(AppDatabase.Schema, ctx, "app.db")
}
}
And the file that I am having issues with - Project/shared/iosMain/kotlin/com/example/sam/data/db/DatabaseDriverFactory.kt
package com.example.sam.data.db
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.drivers.native.NativeSqliteDriver
actual class DatabaseDriverFactory {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(AppDatabase.Schema, "app.db")
}
}
It can't find SqlDriver, NativeSqliteDriver or even com.squareup.*.
I have scoured the web, but didn't find anything that helped.
Comments won't let me post code, but I'd like to try some things.
Try this config and see if the IDE can understand it better. You'll still need to add back some form of the more complex one, but I'd like to reduce the variables as much as possible.
kotlin {
android()
iosX64("ios")
cocoapods {
//etc...
DataStore and preferencesDataStore are absent in this version(beta01).
To do this, you need to:
plugins {
id("com.google.protobuf")
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.17.3"
}
generateProtoTasks {
all().forEach { task ->
task.builtins {
create("java") {
option("lite")
}
}
}
}
implementation("androidx.datastore:datastore-core:1.0.0-beta01")
implementation("com.google.protobuf:protobuf-javalite:3.11.0")
implementation("androidx.preference:preference-ktx:1.1.1")
and initialize
val data: DataStore<SomeMessage> = DataStoreFactory.create(
serializer = SessionSerializer, // your Serializer
corruptionHandler = null,
migrations = emptyList(),
scope = CoroutineScope(Dispatchers.IO + Job())
And continue as before
data.updateData {
it.toBuilder().setAddress("address").build()
}
data.collect { ChargingSession ->
ChargingSession.address
}
Use the below dependency
implementation("androidx.datastore:datastore-preferences:1.0.0-beta01")
I am trying to get https://github.com/Kotlin/kotlinx.serialization to work with my android library I am building using kotlin mpp. This is my gradle file
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.multiplatform")
kotlin("plugin.serialization") version "1.3.61"
}
group = "org.greeting"
version = 1.0
android {
compileSdkVersion(27)
defaultConfig {
minSdkVersion(15)
}
buildTypes {
getByName("release") {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
}
dependencies {
// Specify Kotlin/JVM stdlib dependency.
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7")
implementation(kotlin("stdlib", org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION)) // or "stdlib-jdk8"
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0") // JVM dependency
testImplementation("junit:junit:4.12")
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
androidTestImplementation("junit:junit:4.12")
androidTestImplementation("org.jetbrains.kotlin:kotlin-test")
androidTestImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
kotlin {
android("androidLib")
val buildForDevice = project.findProperty("device") as? Boolean ?: false
val iosTarget = if (buildForDevice) iosArm64("ios") else iosX64("ios")
iosTarget.binaries {
framework {
// Disable bitcode embedding for the simulator build.
if (!buildForDevice) {
embedBitcode("disable")
}
}
}
sourceSets["androidLibMain"].dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0")
}
sourceSets {
commonMain {
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:0.14.0")
}
}
commonTest {
dependencies {
implementation("org.jetbrains.kotlin:kotlin-test-common")
implementation("org.jetbrains.kotlin:kotlin-test-annotations-common")
}
}
}
}
tasks.register("copyFramework") {
val buildType = project.findProperty("kotlin.build.type") as? String ?: "DEBUG"
dependsOn("link${buildType.toLowerCase().capitalize()}FrameworkIos")
doLast {
val srcFile = (kotlin.targets["ios"] as KotlinNativeTarget).binaries.getFramework(buildType).outputFile
val targetDir = project.property("configuration.build.dir")!!
copy {
from(srcFile.parent)
into(targetDir)
include("greeting.framework/**")
include("greeting.framework.dSYM")
}
}
}
tasks.register("iosTest") {
val device = project.findProperty("iosDevice") as? String ?: "iPhone 8"
dependsOn("linkDebugTestIos")
group = JavaBasePlugin.VERIFICATION_GROUP
description = "Runs tests for target 'ios' on an iOS simulator"
doLast {
val binary = (kotlin.targets["ios"] as KotlinNativeTarget).binaries.getTest("DEBUG").outputFile
exec {
commandLine("xcrun", "simctl", "spawn", "--standalone", device, binary.absolutePath)
}
}
}
When I try to run build i get Unresolved reference: serialization on line import kotlinx.serialization.ImplicitReflectionSerializer; But if compile the androidTests the linking works fine. Strangely i have to do sourceSets["androidLibMain"] and can't include it in the sourceSet{} block not sure if this is related. Any ideas on why the build task is not linking my serialization library? Thanks