重命名DocumentDirectory中的文件 [英] Rename file in DocumentDirectory

查看:96
本文介绍了重命名DocumentDirectory中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的DocumentDirectory中有一个PDF文件.

I have a PDF file in my DocumentDirectory.

如果用户愿意,我希望用户能够将此PDF文件重命名为其他名称.

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

我将有一个UIButton开始此过程.新名称将来自UITextField.

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

我该怎么做?我是Swift的新手,只发现了Objective-C信息,并且很难转换它.

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.

文件位置的示例为:

/var/mobile/容器/数据/应用程序/39E030E3-6DA1-45FF-BF93-6068B3BDCE89/Documents/Restaurant.pdf

/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")

        }

推荐答案

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

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

在同一位置使用moveItemAtURL移动文件但使用两个不同的文件名,这与重新命名"的操作相同.

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

简单的例子:

快捷键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)
}

快捷键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)
}

这篇关于重命名DocumentDirectory中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆