从 Swift 的 documentDirectory 中删除所有文件

Remove all files from within documentDirectory in Swift

我正在制作一个音频应用程序,用户可以使用 FileManager 下载本地存储到 documentDirectory 的文件。

接下来,我想允许用户使用一个按钮删除所有文件。在文档中,有一个 method to remove items.

这是我的代码:

@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)
        }
    }

不幸的是,这不会出现错误Ambiguous reference to member 'removeItem(atPath:)'

是否有更好的方法来访问 documentDirectory 并一次性从目录中删除所有文件?

只需使用代码作为关注

将文档目录中的 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
    }

删除

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)
        }
    }

保存方法

getDocumentsDirectory().appendingPathComponent("\(audioName).wav")

删除方法

/// Just call
clearAllFilesFromTempDirectory

试试这个

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)
        }
    }

首先出现错误是因为API的签名错误。只是 removeItem(at:) 没有其他参数。

第二个问题是您要删除 Documents 目录本身,而不是 目录中的文件,您不鼓励这样做。

您必须获取目录的 内容 并添加一个检查,例如仅删除 MP3 文件。更好的解决方案是使用子文件夹。

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) }

旁注:强烈建议始终使用 FileManager 的 URL 相关 API。

这是我的扩展程序,用于从目录中删除所有文件和缓存。

// 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)
            }
        }
    }
}

Swift 5

删除整个文件夹:

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()
}