https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

Avadhut

12/09/2023, 6:08 PM
In Android, we normally store a static JSON files in the
raw
directory, and then it can be accessed as a normal file. What's the equivalent approach for handling such static files in shared KMP code? Thanks!
r

Raed Ghazal

12/09/2023, 6:43 PM
what are the chances, I’m working on that just now 😄
😄 1
so you have 2 options: 1. Moko resources (still trying to implement it right now)
2. doing it natively, in my case I had the json file in
assets
directory, so I accessed it normally from android, then added it to the iosApp directory and accessed it in iosMain natively as well, let me share the snippets
iosMain
Copy code
import kotlinx.cinterop.ExperimentalForeignApi
import platform.Foundation.NSBundle
import platform.Foundation.NSString
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.stringWithContentsOfFile

actual class AssetsReader {
    @OptIn(ExperimentalForeignApi::class)
    actual fun readFile(fileName: String): String {
        val path = NSBundle.mainBundle.pathForResource("data", ofType = "json")
            ?: throw Exception("data.json File not found")
        return NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null)
            ?: throw Exception("failed to encode data.json file")
    }
}
a

Avadhut

12/09/2023, 6:52 PM
Using this way we have to store the json file in each platform's code right? It can't be stored in shared?
r

Raed Ghazal

12/09/2023, 6:54 PM
yes this way it will be stored in each platform on its own, thats what natively basically mean
libraries do the same but behind the scene, they generate the platform specific files from the shared module
btw, androidMain
Copy code
import android.content.Context

actual class AssetsReader constructor(private val context: Context) {
    actual fun readFile(fileName: String): String {
        val file = context.assets.open("quran_data.json")
        return file.bufferedReader().readText()
    }
}
but to save your time if you are okay with using a library for your resouces, use moko resources, makes it easier to have strings, images, assets all in one place (shared module) then the library does the job for you
a

Avadhut

12/09/2023, 6:56 PM
Got it
I'll check both approaches, thanks a lot!
m

McEna

12/10/2023, 9:18 AM
You could go with the platform-based approach and still use a single directory for your files. Just add a gradle task to copy the files from your common directory to the expected destination in both platforms.
💡 1
3 Views