Search code examples
swiftnsfilemanager

Not sure why Swift's fileExists fails on checking existence of a file which I can see in the directory


Part of my app creates files, and then a timer batches them. My problem is that using the fileExists method my app insists that the searched for app does not exist.

I see the files in the Files app, as well as elsewhere in my app where I print all files in the documents directory.

I am wondering if I am perhaps using fileExists property? Although it seems pretty straight forward.

Output from my app:

Creating:
file:///var/mobile/Containers/Data/Application/01793CF4-D50B-4C9D-B4C8-36F916E625BB/Documents/SS-Inventory%20Master%Invoice%2024-08-16gggggg-00000.txt

Checking existence for:
file:///var/mobile/Containers/Data/Application/01793CF4-D50B-4C9D-B4C8-36F916E625BB/Documents/SS-Inventory%20Master%Invoice%2024-08-16gggggg-00000.txt

Where I check if files exists:

//Files are created elsewhere within this path
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first


url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
print(url!.path())

@objc func fireTimer() {
    //build filename here
    var invFileName = String(format: "SS-%@-", invoiceName!)
    let curFileTagName = String(format: "%05d", convertCount)
    let curFileLinkName = String(format: "%@%@.txt", invFileName, curFileTagName)

    var checkPath = url

    checkPath!.append(path: curFileLinkName)

    print("Checking existence for:\n\(checkPath!.absoluteString)")

    if FileManager.default.fileExists(atPath: checkPath!.absoluteString) {
        print ("exists yers")
    } else {
        print ("DOESNOTEXISTS")
    }
}

Solution

  • It fails because you are using the wrong API

    Replace

    if FileManager.default.fileExists(atPath: checkPath!.absoluteString) {
    

    with

    if FileManager.default.fileExists(atPath: checkPath!.path) {
    

    As the name suggests fileExists(atPath expects a path, but absoluteString represents the whole URL including the file:// scheme.

    And use

    url = URL.documentsDirectory
    

    to get the documents folder, the return value is even non-optional.