简体   繁体   中英

Deleting a folder from the documentsDirectory with Swift

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM