Search code examples
iosfilensfilemanager

as I can move all files from one directory to another directory in Objective-C?


as I can move all files from one directory to another directory? I have my code so to move them individually, but I can not move them all.

 NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"user"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];



    NSString *oldPath = [NSString stringWithFormat:@"%@/user/%@", documentsDirectory, fileName];

     NSLog(@"copia de aqui %@", oldPath);
    NSString *newPath = [NSString stringWithFormat:@"%@/leidos/%@", documentsDirectory, fileName];
     NSLog(@"aqui aqui %@", newPath);

    [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];

Solution

  • You could get all the files in the ../user/ directory and store their file names into an array. Then you could loop through the array and move the files to the new directory.

    NSString *oldDirectory = [documentsDirectory stringByAppendingPathComponent:@"user"];
    NSString *newDirectory = [documentsDirectory stringByAppendingPathComponent:@"leidos"];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    // Get all the files at ~/Documents/user
    NSArray *files = [fm contentsOfDirectoryAtPath:oldDirectory error:&error];
    
    for (NSString *file in files) {
        [fm moveItemAtPath:[oldDirectory stringByAppendingPathComponent:file]
                    toPath:[newDirectory stringByAppendingPathComponent:file]
                     error:&differentError];
    }