Yesterday
Yesterday

Reputation: 101

Read/Write file in kotlin native - IOS side


I want to create file and write in with Kotlin/Native on the **IOS side**.

I have this code:

In commonMain :

expect class ReadWriteFile

In androidMain :

actual class ReadWriteFile {
    fun read(path : String, filename: String) : Boolean {
        val file = File("$path/$filename")
        return if(file.exists()) {
            file.forEachLine {
                // do something
            }
            true
        } else {
            false
        }
    }

    fun save(path : String, filename : String, nbLine : Int) {
        val file = File("$path/$filename")
        val w = file.writer()
        for(it in 1..nbLine) {
            w.write("write something\n")
        }
        w.close()
    }
}

In iosMain :

actual class ReadWriteFile {
    fun read(path : String, filename: String) : Boolean {
        ???????????
    }

    fun save(path : String, filename : String, nbLine : Int) {
        ???????????
    }
}

Upvotes: 10

Views: 3252

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88192

Try something like this:

import platform.Foundation.*

class ReadWriteFile {
    fun read(path : String, filename: String) : Boolean {
        val string = NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null) ?: return false
        string.lines().forEach {
            println(it)
        }
        return true
    }

    fun save(path : String, filename : String, nbLine : Int) {
        val result = (1..nbLine).map {
            "string $it"
        }
        (result as NSString).writeToFile(path, true, NSUTF8StringEncoding, null)
    }
}

In general, if you need to find a native solution, its easier to search for an Obj-C one - as kotlin gets converted to it, not Swift, then import platform.Foundation.* or import platform.UIKit.* depending on used classes and adopt to kotlin.

Upvotes: 8

Related Questions