我的电脑里有一个PDF文件DocumentDirectory
.
我希望用户能够将此 PDF 文件重命名为其他名称(如果他们愿意)。
我会有一个UIButton
开始这个过程。新名称将来自UITextField
.
我该怎么做呢?我是 Swift 新手,只找到了有关此的 Objective-C 信息,并且很难转换它。
文件位置的示例是:
/var/mobile/Containers/Data/Application/39E030E3-6DA1-45FF-BF93-6068B3BDCE89/Documents/Restaurant.pdf
我有这个代码来检查文件是否存在:
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")
}
要重命名文件,您可以使用 NSFileManagermoveItemAtURL
.
移动文件moveItemAtURL
在同一位置但具有两个不同的文件名与“重命名”操作相同。
简单的例子:
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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)