Priyanka Kadam
Priyanka Kadam

Reputation: 145

Not able to read json files from Kotlin Multiplatform library working for android but not working for iOS

I'm using KMM library in my project. I want to access local json files in both iOS and Android from shared resources. I don't want to use files from iOS App. I have written following code in shared/src/commonMain/iOSMain but its not working

val bundle = NSBundle.mainBundle
val path = bundle.pathForResource(name = "sample2", ofType = "json") ?: "File not found"

I have put my json files in commonMain/resources/sample2.json I have also try by putting it in commonMain/resources/iOSMain/sample2.json Still its not working. Any suggestions? enter image description here

We have also tried using compose resources inside CommonMain folder depicted in official JetBrains website but not working for iOS

             bytes = Res.readBytes("files/$locale.json").decodeToString()

enter image description here

Upvotes: 2

Views: 273

Answers (1)

Jake Lee
Jake Lee

Reputation: 7989

This is possible using Compose Multiplatform Resources, but everything has to be configured exactly. This is how I'm reading a text file on Android, iOS, and Desktop:

  1. File is in commonMain/composeResources/files/words.txt:

multiplatform resources location

  1. compose.components.resources is added to commonMain dependencies:

compose multiplatform components dependency

  1. Contents is read as a string in a coroutine using:
    @OptIn(ExperimentalResourceApi::class)
    suspend fun readWords(): Map<String, List<Word>> {
        val content = Res.readBytes("files/words.txt").decodeToString()

Upvotes: 0

Related Questions