Check if a File Exist

In this short Swift code example, you will learn how to check if file exists at specified path.

  • Find a Documents directory on device
  • Check if file exists at specified file path
let fileNameToDelete = "myFileName.txt"
var filePath = ""

// Fine documents directory on device
 let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)

if dirs.count > 0 {
    let dir = dirs[0] //documents directory
    filePath = dir.appendingFormat("/" + fileNameToDelete)
    print("Local path = \(filePath)")
} else {
    print("Could not find local directory to store file")
    return
}


let fileManager = FileManager.default

// Check if file exists
if fileManager.fileExists(atPath: filePath) {
    print("File exists")
} else {
    print("File does not exist")
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *