Rename file in DocumentDirectory

ChallengerGuy picture ChallengerGuy · Feb 2, 2016 · Viewed 17.8k times · Source

I have a PDF file in my DocumentDirectory.

I want the user to be able to rename this PDF file to something else if they choose to.

I will have a UIButton to start this process. The new name will come from a UITextField.

How do I do this? I'm new to Swift and have only found Objective-C info on this and am having a hard time converting it.

An example of the file location is:

/var/mobile/Containers/Data/Application/39E030E3-6DA1-45FF-BF93-6068B3BDCE89/Documents/Restaurant.pdf

I have this code to see check if the file exists or not:

        var name = selectedItem.adjustedName

        // Search path for file name specified and assign to variable
        let getPDFPath = paths.stringByAppendingPathComponent("\(name).pdf")

        let checkValidation = NSFileManager.defaultManager()

        // If it exists, delete it, otherwise print error to log
        if (checkValidation.fileExistsAtPath(getPDFPath)) {

            print("FILE AVAILABLE: \(name).pdf")

        } else {

            print("FILE NOT AVAILABLE: \(name).pdf")

        }

Answer

Eric Aya picture Eric Aya · Feb 2, 2016

To rename a file you can use NSFileManager's moveItemAtURL.

Moving the file with moveItemAtURL at the same location but with two different file names is the same operation as "renaming".

Simple example:

Swift 2

do {
    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let documentDirectory = NSURL(fileURLWithPath: path)
    let originPath = documentDirectory.URLByAppendingPathComponent("currentname.pdf")
    let destinationPath = documentDirectory.URLByAppendingPathComponent("newname.pdf")
    try NSFileManager.defaultManager().moveItemAtURL(originPath, toURL: destinationPath)
} catch let error as NSError {
    print(error)
}

Swift 3

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