Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a file using NSFileManager

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 UITextField should be the new filename).

How can I do this?

like image 699
Dipakkumar Avatar asked Aug 17 '10 08:08

Dipakkumar


3 Answers

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];
like image 148
diciu Avatar answered Nov 06 '22 03:11

diciu


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)
}
like image 15
Michal Avatar answered Nov 06 '22 05:11

Michal


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
    }
}
like image 8
victor_luu Avatar answered Nov 06 '22 04:11

victor_luu