Jack Humphries
Jack Humphries

Reputation: 13267

Copy file to different directory

Let's say I have a file at the path /documents/recording.caf and I want to copy it into the folder /documents/folder. How would I do this? If I want to use the following code, it appears as though I have to include the file name and extension in the path, which I will not always know.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *newPath = [documentsDirectory stringByAppendingPathComponent:@"/temporary/recording.caf"];

if ([fileManager fileExistsAtPath:newPath] == NO) {

    [fileManager copyItemAtPath:file toPath:newPath error:&error];

    }

}

A tableview is updated with every file it finds in a directory and if the user taps a cell, I want to copy this file somewhere else.

Upvotes: 0

Views: 390

Answers (1)

MadhavanRP
MadhavanRP

Reputation: 2830

Since the appended path component is also a string, you could use another create another string with the file name that you do not know

NSString *anotherString=[NSString stringWithFormat:@"/temporary/%@",<yourfilenameAsString>];

and just append that to newPath.

I would also suggest that you should not be constructing paths like @"/temporary/filename.extension". But rather, you construct it as using the path construction methods of NSString like

- (NSString *)stringByAppendingPathComponent:(NSString *)aString
- (NSString *)stringByAppendingPathExtension:(NSString *)ext

Upvotes: 3

Related Questions