Search code examples
iosswiftnsfilemanager

FileManager.default.fileExists says documents directory does not exist


FileManager.default.contentsOfDirectory claims that the documents directory does not exist, even though it clearly does. I'm using Swift 4.2 on my actual iPhone SE running iOS 12.1.2

I am reading the contents of the downloads directory in my app using the following:

do {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let downloadedContents = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
    print(downloadedContents)
} catch {
    print("Error while enumerating contents: \(error.localizedDescription)")
}

This prints the following, telling me that a file exists in the documents directory:

[file:///private/var/mobile/Containers/Data/Application/698F8D51-92AF-4BAB-A212-0A0982090550/Documents/example-file/]

(I moved the file there from the caches directory after downloading an in-app purchase, but I don't think that's relevant to this question).

Later in my code, I want to check if the file was downloaded. I'm using the following:

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = URL(fileURLWithPath: "example-file", relativeTo: documentsURL)
var isDir : ObjCBool = false
if FileManager.default.fileExists(atPath: path.standardizedFileURL.absoluteString, isDirectory: &isDir) {
    if isDir.boolValue {
        return true
    } else {
        return false // file exists but is not directory
    }
} else {
    return false // file does not exist at all
}

But this always returns false, even though contentsOfDirectory showed it exists.

While debugging, I also tried:

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
po FileManager.default.fileExists(atPath: documentsURL.standardizedFileURL.absoluteString)

But this, too, returns false. Now I'm pretty sure I'm just using the fileExists methods incorrectly.

Can anyone spot what I'm doing wrong?


Solution

  • Turns out one should use documentsURL.path, instead of any sort of URL.

    The path begins with /var/mobile... whereas the URLs begin with file:///var...