Sergio Andrés Rodríguez Peraza
03/08/2025, 4:26 PMSergio Andrés Rodríguez Peraza
03/08/2025, 4:31 PMclass IosPhotoStorage : PhotoStorage {
@OptIn(ExperimentalForeignApi::class)
private val directory: String
get() =
NSFileManager.defaultManager.URLForDirectory(
directory = NSDocumentDirectory,
inDomain = NSUserDomainMask,
appropriateForURL = null,
create = true,
error = null,
)?.path.orEmpty()
@OptIn(ExperimentalForeignApi::class)
override fun savePhoto(photo: ByteArray): String {
val filename = "${NSUUID.UUID().UUIDString}.jpg"
val filePath = "$directory/$filename"
return try {
val fileManager = NSFileManager.defaultManager
fileManager.createFileAtPath(path = filePath, contents = NSData(), attributes = null)
val fileHandle = NSFileHandle.fileHandleForWritingAtPath(filePath)
fileHandle?.seekToEndOfFile()
fileHandle?.writeData(data = photo.toNSData(), error = null)
fileHandle?.closeFile()
filePath
} catch (e: Exception) {
""
}
}
override fun loadPhoto(path: String): ByteArray? {
return try {
val fileManager = NSFileManager.defaultManager
if (fileManager.fileExistsAtPath(path)) {
NSData.dataWithContentsOfFile(path)?.toByteArray()
} else {
null
}
} catch (e: Exception) {
null
}
}
}
with a byte array i create a NsData and I save it using NSFileManager.defaultManager, I just return the path to the file to save in room db
What is my problem?
When im trying to get many of this photos and then converting the ns data to byte array and the the ui the byte array to image (cause im using ComposeMultiplatform) sometimes the apps crashes and also the files get corrupted and return null
Anyone know how can i improve this approach? migth be a lack of knowledge in ios