HI Team, I want to create a .txt file in iOS usng ...
# multiplatform
g
HI Team, I want to create a .txt file in iOS usng kotlin iosMain. Please help me how to create it. Thanks.
y
here this could help you
Copy code
@OptIn(ExperimentalForeignApi::class)
suspend fun createTextFile(content: String): Result<String> = runCatching {
    withContext(Dispatchers.Default) {
        val fileName = "myText"

        val filePath = "text/$fileName"
        
        //returns an array of directories in the specified domains
        val documentsDirectories = NSSearchPathForDirectoriesInDomains(
            NSApplicationSupportDirectory,
            NSUserDomainMask,
            true,
        )

        //returns the first element of the array
        val documentsDirectory: NSString? = documentsDirectories.firstOrNull() as? NSString

        //returns the path of the file
        val outputFilePath = (documentsDirectory?.stringByAppendingPathComponent(filePath)
            ?: "$documentsDirectory/$filePath").also {
            println("outputFilePath: $it")
        }


        //checks if the file exists
        if (NSFileManager().fileExistsAtPath(outputFilePath)) {
            return@withContext outputFilePath
        }

        //creates a directory called audio
        NSFileManager().createDirectoryAtPath(
            "$documentsDirectory/text",
            true,
            null,
            null,
        )

        //writes file outputFilePath
        (content as NSString).writeToFile(outputFilePath, true)
            .also { success ->
                println("success writing file: $success")
            }
        
        //returns the outputFilePath
        outputFilePath
    }
}
g
ok let me try this thanks