简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM