How to change file name in document folder in swift

Viewed 1438

I have some files located at my document folder. I am saving the files like "data_20201223163209.pdf", "data_20201223171831.pdf", "data_20201222171831.pdf", "data_20201221171831.pdf" etc. Now I want to replace "data" with other strings like "newdata". So my files should be "newdata_20201223163209.pdf", "newdata_20201223171831.pdf", "newdata_20201222171831.pdf", "newdata_20201221171831.pdf"

My code:

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

Please help me resolve this issue

1 Answers

You just need to get the contents of your directory, filter the urls which names starts with "data_", iterate those urls and rename each one moving it to the same directory with the new name. Note that this assumes there is no file at the destination with the new names.

// 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 { $0.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)
}
Related