0

I am looking for a proper way to definitively check if an URL points to a file or a directory. Files should include filewrapped data like UIDocument using a FileWrapper to wrap its underlying structure.

I am aware of the fact that URLResourceValues allows checking for isDirectory and isRegularFile via

let resourceValues = try? url.resourceValues(forKeys: [.isRegularFileKey, .isDirectoryKey])
resourceValues?.isDirectory
resourceValues?.isRegularFile

But in the case of a filewrapped document with a directory substructure isDirectory would be true but isRegularFile would be false, so this does not help.

The one solution I could come up with is to use documentIdentifier like

let resourceValues = try? url.resourceValues(forKeys: [.documentIdentifierKey])
resourceValues?.documentIdentifier // non-nil if url points to file, nil otherwise

which works fine for me: documentIdentifier is nil for a directory and non-nil for a file.

So my question is: Is using URLResourceValues with documentIdentifier a proper solution for checking if an URL points to a file or a directory or is there a preferred way to do this?

Wizard
  • 295
  • 1
  • 4
  • 15
  • You can check if the file is a [package](https://developer.apple.com/documentation/foundation/urlresourcekey/1413867-ispackagekey). You can also get its parent url and check if it is a package – Leo Dabus Feb 21 '22 at 21:17
  • @Wizard "Files should include filewrapped data" - this is not possible because a file is a storage unit and a folder contains several storage units. FileWrapped files/packages etc. are just folders that are treated as a file by the Finder. You can easily validate that in the terminal using `ls -lrth yourUrl`. Extensions aren't limited to files so folder can have them as well. You can check if your url is a folder and optionally if it has the correct extension. e.g.: if you have a custom extension like .myDocument – DoTryCatch Feb 21 '22 at 22:13
  • @DoTryCatch Thanks for your reply. I am aware of what you wrote. I used the term file in the sense of how finder treats it. Your suggestion only works if you know exactly what extensions to check for. I was wondering if there is a general standard solution to the problem as checking via `documentIdentifier` feels like it might not be the intended way to do it. – Wizard Feb 22 '22 at 10:26
  • @Wizard you could check the UTI typIdentifier like here: https://stackoverflow.com/questions/28570627/how-to-find-file-uti-for-file-withouth-pathextension-in-a-path-in-swift and check if it conform to "com.apple.package" but this might be not accurate as well if you want to check custom files. – DoTryCatch Feb 22 '22 at 10:53
  • For now I am happy with @LeoDabus proposal. It seems to be a better way than using `documentIdentifier`. But maybe someone has some additional input on that. – Wizard Feb 22 '22 at 11:27

0 Answers0