Cha*_*Guy 22 file-rename ios swift
我有一个PDF文件DocumentDirectory
.
我希望用户能够将此PDF文件重命名为其他内容(如果他们选择).
我将有一个UIButton
开始这个过程.新名称将来自a 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")
}
Run Code Online (Sandbox Code Playgroud)
aya*_*aio 39
要重命名文件,您可以使用NSFileManager moveItemAtURL
.
使用moveItemAtURL
相同位置但使用两个不同文件名移动文件与"重命名"操作相同.
简单的例子:
斯威夫特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)
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特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)
}
Run Code Online (Sandbox Code Playgroud)
现代方法是 (url
是沙箱中文件的文件 URL):
var rv = URLResourceValues()
rv.name = newname
try? url.setResourceValues(rv)
Run Code Online (Sandbox Code Playgroud)
小智 5
在任何给定的NSURL处都有一种更简单的方法来重命名项目。
url.setResourceValue(newName, forKey: NSURLNameKey)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12384 次 |
最近记录: |