39

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?

Michal
  • 14,455
  • 9
  • 68
  • 97
Dipakkumar
  • 717
  • 1
  • 6
  • 14

4 Answers4

84

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];
Pang
  • 8,605
  • 144
  • 77
  • 113
diciu
  • 28,395
  • 4
  • 48
  • 68
  • This is moving file from one folder to another, anyways it's working but when there is space in the filename it's not working. ex: **Path:: /tmp/test file.tt toPath: /tmp/dst path.tt** it's an url space is automatically converting to %20. Is there any other possibulity renaming folder without URL/moving.?? – MIOSY Nov 04 '19 at 06:49
15

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)
}
Pang
  • 8,605
  • 144
  • 77
  • 113
Michal
  • 14,455
  • 9
  • 68
  • 97
5

This is the function by daehan park to converted to Swift 3:

func moveFile(pre: String, move: String) -> Bool {
    do {
        try FileManager.default.moveItem(atPath: pre, toPath: move)
        return true
    } catch {
        return false
    }
}
Pang
  • 8,605
  • 144
  • 77
  • 113
victor_luu
  • 99
  • 1
  • 2
1

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
    }
}
Pang
  • 8,605
  • 144
  • 77
  • 113
daehan park
  • 88
  • 1
  • 7