6

I need a 100% fail-safe way to determine if a file name/file URL is available for writing data to disk without accidentally deleting an existing file.

Currently I'm using NSFileManager.fileExists(atPath:), but I'm wondering, what if the parent directory is in iCloud and my file URL points to an existing file in iCloud that hasn't been downloaded to the device yet?

What got me thinking are these two methods of URL:

  • func checkResourceIsReachable() throws -> Bool
  • func checkPromisedItemIsReachable() throws -> Bool

There is a distinction between a resource and a promised item. A promised item is defined as:

A promised item is not guaranteed to have its contents in the file system until you use a file coordinator to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated.

Background:

What I'm after is an extension for FileManager that returns the next available, non-existing file name for a given (existing) file URL. For example:

  • Let's say my existing document is: /documents/Text.txt
  • The next available file name could be: /documents/Text 2.txt

How can I check that Text 2.txt really doesn't exist locally and in iCloud?

Here's my current approach:

// Safer than: FileManager.default.fileExists(at: url) ?
private func fileExists(at url:URL) throws -> Bool
{
    if (try url.resourceValues(forKeys: [.isUbiquitousItemKey])).isUbiquitousItem == true
    {
        return try url.checkPromisedItemIsReachable()
    }
    else
    {
        return try url.checkResourceIsReachable()
    }
}
Mark
  • 6,647
  • 1
  • 45
  • 88

0 Answers0