How to delete file using Swift programming

To delete a file on your computer using Swift programming, you must utilize Swift extensions and use the FileManager¬†framework in order to access, modify or remove files from the local system. In the following example, we will be using the _removeItem(at URL: URL) function to permanently delete items from the user’s computer.

Setting up the application

To run this application on your computer, open an Xcode Playground project, as it allows the most mobility and access to all Xcode Frameworks.

In this specific example, we will be deleting an image (.png), but you can delete all types of files using this function.

This method works easiest if the file is saved on your desktop, but if not you must remember the path directory and exact name of the file.

Creating the extension

Firstly, to convert the file as an object in Swift, you must initialize the name and extension of the file so that it can be identified and used for later use. This can be done using the following code:

extension String {
    func getFileName() -> String {
        return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
    }
    
    func getFileExtension() -> String {
        return URL(fileURLWithPath: self).pathExtension
    }
}
  • The function getFileName returns the name of the file so that it can be easily understood in our future functions. For example, for a file path like /Desktop/NewFolder/image.png, this function simply converts it into “image”.
  • The function getFileExtension returns the type of file being used, so it can identify what type of file needs to be deleted. Following the previous example, for a file path like /Desktop/NewFolder/image.png,t his function simply returns “.png”.

Creating this extension will make it easier to access the files later, and makes it more convenient to use just the name rather than writing the entire path.

Creating the deleting function to delete a file in Swift

To delete a function, we must implement the file manager framework to access the file. This is done using:

func deleteFiles(_ fileToDelete: String) {
        let fName = fileToDelete.getFileName()
        let fExtension = fileToDelete.getFileExtension()
        
        let fURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        
        let deleteAtURL = fURL.appendingPathComponent(fName).appendingPathExtension(fExtension)
        
        do {
            try FileManager.default.removeItem(at: deleteAtURL)
            print("Image has been deleted")
        } catch {
            print(error)
        }
    }
  • First, you must create a variable for the name and extension from the input “fileToDelete” from the user. Here, “fName” is used to store the file name, and “fExtension” to store the file extension.
  • To locate this on the computer, we access the FileManager framework simply by typing “FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: false). (Note: the parameter for: is set to .desktopDirectory because the file is on the desktop. If your file is stored somewhere else, use the appropriate directory like documents.Directory for example)
  • The “.userDomainMask” searches for the file within the directory entered in parameter 1, “appropriateFor” limits and controls the number of directories that can be passed, and “create” creates a file if the input file name does not exist.
  • The variable “deleteAtURL” adjusts the file name and extension so it follows the format of the removeItem(at URL: URL).
  • The try FileManager.default.removeItem(at: deleteAtURL) is placed inside of a do-catch method, in case no file is found this allows the application to print the error in the debug pane instead of crashing the application.

Take file path as Input to delete

deleteFiles("DeletingFile.png")

To delete a file, simply call the deleteFiles() method, and set the parameter as the name of the file with the extension that you wish to delete.  Running this program will now delete the file!

 

(Optional) Test Run

Click on the image to maximize it

delete a file in Swift

 

Want to learn how to use conditional cases in Swift? If NOT Conditional case in Swift

Leave a Reply

Your email address will not be published.