iconso
iconso

Reputation: 275

Copy contents of a directory to Documents directory

I have a problem, I need to move the contents of a Documents subdirectory to the 'root' of Documents Directory. To do this, I thought to copy all the contents of the subdirectory to Documents directory and then delete my subdirectory.

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"]

This is how I get the path of Documents directory, and the path of my subdirectory named inbox.

 NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentinbox error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];

Then I create an array with all documents in the subfolder, and initialize the file manager.

Now I have to implement the for cycle that for each document copy the document from the subdirectory to the Documents Directory.

for(int i=0;i<[inboxContents count];i++){
  //here there is the problem, I don't know how to copy each file

I would like to use the method moveItemAtPath, but I don't know how to get the path of each file.

Hope you can understand my problem, Thanks for help Nicco

Upvotes: 0

Views: 1786

Answers (1)

Joe
Joe

Reputation: 57179

You can use moveItemAtPath:toPath:error: as follows.

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"];

//Initialize fileManager first
NSFileManager *fileManager = [NSFileManager defaultManager];

//You should always check for errors
NSError *error;
NSArray *inboxContents = [fileManager contentsOfDirectoryAtPath:documentinbox error:&error];
//TODO: error handling if inboxContents is nil

for(NSString *source in inboxContents)
{
    //Create the path for the destination by appending the file name
    NSString *dest = [documentsDirectory stringByAppendingPathComponent:
                      [source lastPathComponent]];

    if(![fileManager moveItemAtPath:source
                            toPath:dest
                             error:&error])
    {
        //TODO: Handle error
        NSLog(@"Error: %@", error);
    }
}

Upvotes: 2

Related Questions