Skip to content

Commit

Permalink
#44 file resource runtime draft
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex009 committed May 3, 2020
1 parent da05560 commit 38e851d
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/

package dev.icerock.moko.resources

import java.io.File
import java.net.URI

actual class FileResource(
val assetsPath: String
) {
actual fun readText(): String {
val assetUri: URI = URI.create("file:///android_asset/$assetsPath")
val file: File = File(assetUri)
return file.readText()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/

package dev.icerock.moko.resources

expect class FileResource {
fun readText(): String
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/

package dev.icerock.moko.resources

import kotlinx.cinterop.ObjCObjectVar
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.value
import platform.Foundation.NSBundle
import platform.Foundation.NSError
import platform.Foundation.NSString
import platform.Foundation.NSURL
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.stringWithContentsOfFile

actual class FileResource(
val fileName: String,
val bundle: NSBundle = NSBundle.mainBundle
) {
val path: String get() = bundle.pathForResource(name = fileName, ofType = null, inDirectory = "files")!!
val url: NSURL get() = bundle.URLForResource(name = fileName, withExtension = null, subdirectory = "files")!!

actual fun readText(): String {
val (result: String?, error: NSError?) = memScoped {
val p = alloc<ObjCObjectVar<NSError?>>()
val result: String? = runCatching {
NSString.stringWithContentsOfFile(
path = path,
encoding = NSUTF8StringEncoding,
error = p.ptr
)
}.getOrNull()
result to p.value
}

if (error != null) throw RuntimeException(error.localizedDescription)
else return result!!
}
}

0 comments on commit 38e851d

Please sign in to comment.