Search code examples
iosobjective-cfile-rename

How to rename files/folders from document folder programmatically in iOS


I am working on functionality to save video files in document folder of application in iOS.

How to rename some files programmatically?


Solution

  • try this code :

    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);
    

    other wise use this method to rename file

    - (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];
        NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:filePathSrc]) {
            NSError *error = nil;
            [manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];
            if (error) {
                NSLog(@"There is an Error: %@", error);
            }
        } else {
            NSLog(@"File %@ doesn't exists", srcName);
        }
    }