Search code examples
swiftmacosswift5nsfilemanager

How would I check for a file in a specified directory in Swift 5?


I'm trying to verify that a file is present in the Downloads folder of the user. I have already enabled access to the Downloads folder in the permissions. Here's what I tried so far:

        let path = "~/Downloads/Game_Folder/GameFile.obb"
        let hasFile = FileManager().fileExists(atPath: path)
        if hasFile {
            installationLabel.stringValue = "Game Files Found!"
        }
        else {
            installationLabel.stringValue = "Game Files Not Found"
        } 

It will always say "Game files not found" when testing. I haven't found a definitive solution for this in Swift 5 yet, so that's why I'm asking.

Thanks for the help!


Solution

  • Figured it out. Here's what I put for Swift 5.

    let path = NSString(string: "~/test-node.js").expandingTildeInPath
    let fileDoesExist = FileManager.default.fileExists(atPath: path)
    

    The "~/test-node.js" should be replaced with the path of the file you want to verify exists.