从Swift中的documentDirectory中删除所有文件

时间:2018-04-25 04:26:31

标签: ios swift nsdocumentdirectory

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

接下来,我想允许用户使用按钮删除所有文件。在文档中,有一个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并一举删除目录中的所有文件?

4 个答案:

答案 0 :(得分:4)

首先发生错误是因为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, .skipsSubdirectoryDescendants])
    for fileURL in fileURLs {
        if fileURL.pathExtension == "mp3" {
            try FileManager.default.removeItem(at: fileURL)
        }
    }
} catch  { print(error) }

附注:强烈建议始终使用FileManager的网址相关API。

答案 1 :(得分:2)

只需使用代码<\ n>

将AudioFile保存为文档目录

$userRoles

删除

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

答案 2 :(得分:1)

试试这个

html5 geolocation API

答案 3 :(得分:0)

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

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