Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all files from within documentDirectory in Swift

I am making an audio app, and the user can download files locally stored to the documentDirectory using FileManager.

Next, I'd like to allow the user to delete all files using a button. In the documentation, there is a method to remove items.

Here's my code:

@IBAction func deleteDirectoryButton(_ sender: Any) {

    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        do {
            try FileManager.default.removeItem(at: documentsUrl, includingPropertiesForKeys: nil, options: [])

        } catch let error {
            print(error)
        }
    }

Unfortunately, this won't build with an error Ambiguous reference to member 'removeItem(atPath:)'.

Is there a better approach to access the documentDirectory and remove all files from the directory in one swoop?

like image 471
darkginger Avatar asked Apr 25 '18 04:04

darkginger


1 Answers

First of all the error occurs because the signature of the API is wrong. It's just removeItem(at:) without the other parameters.

A second issue is that you are going to delete the Documents directory itself rather than the files in the directory which you are discouraged from doing that.

You have to get the contents of the directory and add a check for example to delete only MP3 files. A better solution would be to use a subfolder.

let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsUrl,
                                                               includingPropertiesForKeys: nil,
                                                               options: .skipsHiddenFiles)
    for fileURL in fileURLs where fileURL.pathExtension == "mp3" {
        try FileManager.default.removeItem(at: fileURL)   
    }
} catch  { print(error) }

Side note: It is highly recommended to use always the URL related API of FileManager.

like image 193
vadian Avatar answered Sep 19 '22 23:09

vadian