Monitor file with some kind of persistent id

Viewed 55

My app writes files to the users shared Documents directory. I save the files path but this breaks if the user changes the documents name, moves the document to a new location etc. Is there some kind of persistent file id i can use to keep track of these documents? i've been poking around

FileManager.default.attributesOfItem(atPath: docUrl.path)

and i find attributes like FileAttributeKey.systemFileNumber but this number seems to change every time i run the app. There has to be some way to keep track of files other than their path

1 Answers

You need to use url bookmarks, like the following (sketch)

if let bookmark = try? URL(fileURLWithPath: docUrl.path)
                         .bookmarkData(includingResourceValuesForKeys: nil, 
                                       relativeTo:nil) {
    // store somewhere persistent bookmark to your file
}

... 

let bookmark = // read bookmark from persisten storage
var stale = false
if let url = try? URL(resolvingBookmarkData:bookmark, bookmarkDataIsStale: &stale) {
    // work with resolved url
} else {
    // file disappeared - handle the situation
}
Related