重命名 DocumentDirectory 中的文件

Rename file in DocumentDirectory

我的 DocumentDirectory 中有一个 PDF 文件。

我希望用户能够将此 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")

        }

要重命名文件,您可以使用 NSFileManager 的 moveItemAtURL

将带有 moveItemAtURL 的文件移动到同一位置但具有两个不同的文件名与 "renaming" 的操作相同。

简单示例:

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

有一种更简单的方法可以重命名任何给定 NSURL 的项目。

url.setResourceValue(newName, forKey: NSURLNameKey)

编辑 - Swift4

url.setTemporaryResourceValue(newName, forKey: .nameKey)

现代方式是(url 是沙盒中文件的 URL 文件):

var rv = URLResourceValues()
rv.name = newname
try? url.setResourceValues(rv)