swift 如何更改文档文件夹中的文件名

How to change file name in document folder in swift

我的文档文件夹中有一些文件。我正在保存“data_20201223163209.pdf”、“data_20201223171831.pdf”、“data_20201222171831.pdf”、“data_20201221171831.pdf”等文件。现在我想用其他字符串替换“data”像“新数据”。所以我的文件应该是“newdata_20201223163209.pdf”、“newdata_20201223171831.pdf”、“newdata_20201222171831.pdf”、“newdata_20201221171831.pdf”

我的代码:

do {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let documentDirectory = URL(fileURLWithPath: path)
    let originPath = documentDirectory.appendingPathComponent("data")
    let destinationPath = documentDirectory.appendingPathComponent("newdata")
    try FileManager.default.moveItem(at: originPath, to: destinationPath)
} catch {
    print(error)
}

请帮我解决这个问题

您只需要获取目录的内容,过滤名称以“data_”开头的网址,迭代这些网址并重命名每个网址,将其移动到具有新名称的同一目录。请注意,这假定目的地没有使用新名称的文件。

// Get the documents url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
    // Get its contents
    let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(contents)
    // filter the contents that starts with "data_"
    let dataFiles = contents.filter { [=10=].lastPathComponent.hasPrefix("data_") }
    // iterate the source files
    for srcURL in dataFiles {
        // create the destinations appending "newdata_" + the source lastPathComponent dropping its "data_" prefix
        let dstURL = documentsUrl.appendingPathComponent("newdata_" + srcURL.lastPathComponent.dropFirst(5))
        // move/rename your files
        try FileManager.default.moveItem(at: srcURL, to: dstURL)
    }
} catch {
    print(error)
}