[英]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
.我正在制作一个音频应用程序,用户可以使用
FileManager
下载本地存储到documentDirectory
的文件。
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 .
在文档中,有一种方法可以删除 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:)'
.不幸的是,这不会生成错误
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?有没有更好的方法来访问
documentDirectory
并一次性从目录中删除所有文件?
First of all the error occurs because the signature of the API is wrong.首先出现错误是因为API的签名错误。 It's just
removeItem(at:)
without the other parameters.它只是
removeItem(at:)
没有其他参数。
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.第二个问题是,你要删除
Documents
目录本身,而不是你从这样做,鼓励在目录中的文件。
You have to get the contents of the directory and add a check for example to delete only MP3 files.您必须获取目录的内容并添加检查,例如仅删除 MP3 文件。 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 {
if 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
.旁注:强烈建议始终使用
FileManager
的 URL 相关 API。
Just use code as Follow只需使用代码作为关注
to save AudioFile in Document Directory as将文档目录中的 AudioFile 保存为
func getDocumentsDirectory() -> URL
{
//Get Basic URL
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
/// Enter a Directory Name in which files will be saved
let dataPath1 = documentsDirectory.appendingPathComponent("folder_name_enter")
let dataPath = dataPath1.appendingPathComponent("folder inside directory if required (name)")
//Handler
do
{
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
print("Error creating directory: \(error.localizedDescription)")
}
return dataPath
}
Delete删除
func clearAllFilesFromTempDirectory()
{
let fileManager = FileManager.default
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let tempDirPath = dirPath.appending("/folder_name/\(inside_directoryName)")
do {
let folderPath = tempDirPath
let paths = try fileManager.contentsOfDirectory(atPath: tempDirPath)
for path in paths
{
try fileManager.removeItem(atPath: "\(folderPath)/\(path)")
}
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
Saving Method保存方法
getDocumentsDirectory().appendingPathComponent("\(audioName).wav")
Deletion Method删除方法
/// Just call
clearAllFilesFromTempDirectory
Try this尝试这个
func clearAllFile() {
let fileManager = FileManager.default
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
print("Directory: \(paths)")
do
{
let fileName = try fileManager.contentsOfDirectory(atPath: paths)
for file in fileName {
// For each file in the directory, create full path and delete the file
let filePath = URL(fileURLWithPath: paths).appendingPathComponent(file).absoluteURL
try fileManager.removeItem(at: filePath)
}
}catch let error {
print(error.localizedDescription)
}
}
This my extension for remove all files and caches from directory.这是我的扩展,用于从目录中删除所有文件和缓存。
// MARK: - FileManager extensions
extension FileManager {
/// Remove all files and caches from directory.
public static func removeAllFilesDirectory() {
let fileManager = FileManager()
let mainPaths = [
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).map(\.path)[0],
FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).map(\.path)[0]
]
mainPaths.forEach { mainPath in
do {
let content = try fileManager.contentsOfDirectory(atPath: mainPath)
content.forEach { file in
do {
try fileManager.removeItem(atPath: URL(fileURLWithPath: mainPath).appendingPathComponent(file).path)
} catch {
// Crashlytics.crashlytics().record(error: error)
}
}
} catch {
// Crashlytics.crashlytics().record(error: error)
}
}
}
}
If you'd like to delete a whole folder you can simply do this:
如果你想删除整个文件夹,你可以简单地这样做:
func deleteFolder(_ folderName: String, completion: () -> Void) {
let fileManager = FileManager.default
let directory = fileManager.cachesDirectory().appendingPathComponent(folderName)
_ = try? fileManager.removeItem(at: directory)
completion()
}
This will loop through all the files and remove all that contain the
这将遍历所有文件并删除所有包含
func removeFiles(containing: String, completion: () -> Void) {
let fileManager = FileManager.default
let directory = fileManager.cachesDirectory()
if let fileNames = try? fileManager.contentsOfDirectory(atPath: directory.path) {
for file in fileNames {
if file.contains(containing) {
let filePath = URL(fileURLWithPath: directory.path).appendingPathComponent(file).absoluteURL
_ = try? fileManager.removeItem(at: filePath)
}
}
}
completion()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.