简体   繁体   English

使用 Swift 从文档目录中删除文件夹

[英]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:我在文档目录中创建了一个 VideoAssets 文件夹,如下所示,其中可以包含一个或多个视频资产:

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?如何清空文件夹或删除整个 VideoAssets 文件夹? 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)只需使用try FileManager.default.removeItem(at: directoryUrl)

From Apple's docs:来自苹果的文档:

A file URL specifying the file or directory to remove.指定要删除的文件或目录的文件 URL。 If the URL specifies a directory, the contents of that directory are recursively removed.如果 URL 指定了一个目录,则该目录的内容将被递归删除。 You may specify nil for this parameter.您可以为此参数指定 nil。

https://developer.apple.com/documentation/foundation/filemanager/1413590-removeitem 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.在调用FileManager.default.fileExists(atPath: directory)我错误地传递了 URL 而不是字符串,而且还必须先删除file://

I was then able to successfully delete a file within the newly created folder using removeItem: try FileManager.default.removeItem(atPath: directoryUrl)然后我能够使用 removeItem 成功删除新创建的文件夹中的文件: try FileManager.default.removeItem(atPath: directoryUrl)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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