ChallengerGuy ChallengerGuy - 1 year ago 69
Swift Question

Rename file in DocumentDirectory

I have a PDF file in my


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

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

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:


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 Source

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 {

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 {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download