Delete File Example in Swift

In this short tutorial, you will learn how to Delete a file from the Documents directory using Swift. The below code will cover:

  • Find a Documents directory on the device,
  • Check if a file at the specified path exists,
  • Delete file,
  • Catch an error if an error takes place.
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
}


do {
     let fileManager = FileManager.default
    
    // Check if file exists
    if fileManager.fileExists(atPath: filePath) {
        // Delete file
        try fileManager.removeItem(atPath: filePath)
    } else {
        print("File does not exist")
    }
 
}
catch let error as NSError {
    print("An error took place: \(error)")
}

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 *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!