Read local file from project directory | Kotlin Multiplatform Mobile | KMM

Viewed 1989

I am trying to read JSON file which is saved in my project locally and want to fetch and read using Kotlin Multiplatform Mobile, so I can share with Android and iOS

Following approch I'm doing:

In commonMain :

package com.example.readJSON.shared

import kotlinx.serialization.Serializable

@Serializable
data class DataRequest(
    val dataRegimenRequest: List<DataRegimenRequest>?
)

expect class FileResource(location: String){
    val json: String?
}

In androidMain :

package com.example.readJSON.shared

actual class FileResource actual constructor(location: String) {
    actual val json: String? = this::class.java.classLoader!!.getResource(location)?.readText()
}

In iosMain :

package com.example.readJSON.shared

actual class FileResource actual constructor(location: String) {
    actual val json: String? = null //TODO: write a code to read from local file
}

Can someone will help me, how can I fetch my local JSON file for iOS?

For Android, I am able to read local JSON file.

1 Answers

You'll probably need to write some gradle to copy the file to your iOS app source, then load it by reading iOS resource files from the Bundle. It's a little hard to follow, but we push in a Swift function to handle that here. You could write that code in iOS Kotlin as well.

You might be able to add the file to Xcode directly without needing to copy it in Gradle. From Xcode, right-click your source folder and select "Add Files to ___", then point it at the file. If all of your source is in a single repo, you should be able to point at that file with a relative path from Xcode, and load it at runtime.

For Android, you'd probably want to put that file in assets rather than load it with the class loader, but that's a different discussion.

Related