I have a single file named a.caf in the documents directory. I would like to rename it when user types into a UITextField
and presses change (the text entered in the UIText开发者_如何学CField
should be the new filename).
How can I do this?
You can use moveItemAtPath.
NSError * err = NULL;
NSFileManager * fm = [[NSFileManager alloc] init];
BOOL result = [fm moveItemAtPath:@"/tmp/test.tt" toPath:@"/tmp/dstpath.tt" error:&err];
if(!result)
NSLog(@"Error: %@", err);
[fm release];
To keep this question up-to-date, I'm adding the Swift version as well:
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let originPath = documentDirectory.stringByAppendingPathComponent("/tmp/a.caf")
let destinationPath = documentDirectory.stringByAppendingPathComponent("/tmp/xyz.caf")
var moveError: NSError?
if !manager.moveItemAtPath(originPath, toPath: destinationPath, error: &moveError) {
println(moveError!.localizedDescription)
}
This is the function by daehan park to converted to Swift 3 and works with Swift 4 & 5:
func moveFile(pre: String, move: String) -> Bool {
do {
try FileManager.default.moveItem(atPath: pre, toPath: move)
return true
} catch {
return false
}
}
Worked on Swift 2.2
func moveFile(pre: String, move: String) -> Bool {
do {
try NSFileManager.defaultManager().moveItemAtPath(pre, toPath: move)
return true
} catch {
return false
}
}
精彩评论