When users share a file with my app I am having trouble 5-10% of the time obtaining the file meta data, specifically creation and modified time and size.
Using SwiftUI with the code below..
.onOpenURL { url in
var fileSize: Int64 = 0
var creationTime: Date = Date(timeIntervalSince1970: 0)
var modificationTime: Date = Date(timeIntervalSince1970: 0)
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: url.path)
fileSize = fileAttributes[FileAttributeKey.size] as? Int64 ?? 0
creationTime = fileAttributes[FileAttributeKey.creationDate] as? Date ?? Date(timeIntervalSince1970: 0)
modificationTime = fileAttributes[FileAttributeKey.modificationDate] as? Date ?? Date(timeIntervalSince1970: 0)
<SNIPPED CODE no other tries though and not involving above variables>
} catch {
// quite confident I am ending up here because variables after the above code aren’t being set and there are no other try blocks,
// so FileManager.default.attributesOfItem(atPath: url.path) must be throwing….
}
<SNIPPED CODE>
To attempt to resolve this, I added in a 0.5 second wait cycle if creationTime == 0 and modificationTime == 0 , so if obtaining both metadata fails, wait 0.5 seconds and try again, try this a max of 3 times and then give up. I don’t know how often I am entering this code (didn’t instrument the app for it), but am still getting times when metadata comes back blank which means this code wasn’t successful after 3 tries.
I assume the file would only become visible and sharable with my app after it has completed being written by the original app/process. Perhaps it hasn’t finalized yet? Is there a way to detect this so I can tell the user in my share screen to wait and try again?
I am assuming that the file has finished writing though since when I read the data from the file contents, it’s good data and complete even when metadata failed.
I will be instrumenting the above code in my next app version, just hoping to fix it right now since users are emailing saying my app is broken.
Thanks!