Alexis
02/11/2025, 7:03 PM@OptIn(ExperimentalForeignApi::class)
class FileDownloaderServiceImpl: FileDownloaderService {
override suspend fun saveFile(data: ByteArray, folder: String, name: String): String? {
// Get the app's document directory
val fileManager = NSFileManager.defaultManager
val documentDirectory = fileManager.URLForDirectory(
directory = NSDocumentDirectory,
inDomain = NSUserDomainMask,
appropriateForURL = null,
create = true,
error = null
) ?: throw IllegalStateException("Could not access document directory")
// Create the file path
val filePath = documentDirectory.URLByAppendingPathComponent("${folder.removePrefix("/")}/$name")?.path ?: throw IllegalStateException("Invalid file path")
val nsData = data.toNSData()
return if (nsData.writeToFile(filePath, true)) filePath
else null
}
// Helper extension to convert ByteArray to NSData
@OptIn(BetaInteropApi::class)
private fun ByteArray.toNSData(): NSData {
return this.usePinned { pinned ->
NSData.create(bytes = pinned.addressOf(0), length = this.size.toULong())
}
}
}
I use it to save images, but I can't load these images afterward and when I look at the container of my app within XCode, it seems that the files are missing.
I'm trying to debug it, but I'm really not used to the ios development tools.