Deleting a folder from the documentsDirectory with Swift

3.4k views Asked by At

I have created a VideoAssets folder within documentsDirectory as below, which can contain one or more video assets:

file:///private/var/mobile/Containers/Data/Application/2E3H5FDD-825D-407A-A8BE-71CD540A6E15/Documents/VideoAssets/ae6e4f59be0bc5984b043e.mp4

Periodically it needs to be cleaned out. How can I either empty the folder OR remove the VideoAssets folder in it's entirety? There's a fair bit of info out there for creating folders, but not for removing one.

2

There are 2 answers

1
aasatt On

Just use try FileManager.default.removeItem(at: directoryUrl)

From Apple's docs:

A file URL specifying the file or directory to remove. If the URL specifies a directory, the contents of that directory are recursively removed. You may specify nil for this parameter.

https://developer.apple.com/documentation/foundation/filemanager/1413590-removeitem

0
AudioBubble On

In answer to my own question:

When calling FileManager.default.fileExists(atPath: directory) I was erroneously passing a URL and not a string, but also file:// had to be removed first.

I was then able to successfully delete a file within the newly created folder using removeItem: try FileManager.default.removeItem(atPath: directoryUrl)