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")
}
It is also better use QFile::rename(const QString & oldName, const QString & newName) to rename a file. When using QDir::rename, If oldName is a file (not a directory) that can't be renamed right away, Qt will try to copy oldName to newName and remove oldName.
Renaming Swift codeThe renaming refactoring option can be selected from the refactoring menu by right-clicking the piece of Swift code you want to rename. It will open a new edit overview which will show all the references which will be renamed across multiple files.
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)
}
The modern way is (url
is the file URL of a file in your sandbox):
var rv = URLResourceValues()
rv.name = newname
try? url.setResourceValues(rv)
There is an easier way to rename item at any given NSURL.
url.setResourceValue(newName, forKey: NSURLNameKey)
Edit - Swift4
url.setTemporaryResourceValue(newName, forKey: .nameKey)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With