Copy file to different directory - iphone

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.

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

Related

How to get the title of the metadata which is placed in directories in resources folder

i am new to iphone programming. i want to get the title of mp3 file which is located in directory of Resourse folder
Resourse Folder Structure is following
Resourse
raj(directory)---->1.mp3
---->2.mp3
Here i know to get the path of the file if i get path it shows like this
/Users/Chary/Library/Application Support/iPhone Simulator/5.0/Applications/B02404E5-52DC-49B6-8DBB-C9946E4331AF/BiblePlayer.app/raj/1.mp3
I have a picker view in that i have to show only title like as "1","2" for 1.mp3 and 2.mp3
but how can get like this it will show the entire path
so,if any body know this please help me.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
//Provide another path if you have folder in your directory
NSArray *arrDirVideos = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
It will give all files for path you provided in array like { 1.mp3,2.mp3,..} So now u can elimate .mp3 from each item of array
Use this:
NSString * mp3FilePath = [[NSBundle mainBundle]
pathForResource:#"1"
ofType:#"mp3"];

Obj-C, how do I copy a file with NSSearchPathForDirectoriesInDomains?

I want to copy some files as part of a backup routine.
I have the following function which gives the location of my files.
- (NSString *)getLocalDocumentPath:(NSString*)strFile {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0]
stringByAppendingPathComponent:strFile];
return path;
}
Heres my database
NSString *filePath = [self getLocalDocumentPath:#"mydatabase.db"];
I want to copy this to a new file called upload.txt
NSString *filePath = [self getLocalDocumentPath:#"upload.txt"];
Then later on I download a file.
NSString *filePath = [self getLocalDocumentPath:#"download.txt"];
Which I want to copy on top of my original database file.
NSString *filePath = [self getLocalDocumentPath:#"mydatabase.db"];
NSFileManager *fileManager = [NSFilemanager defaultManager];
[fileManager copyItemAtPath:databasePath toPath:uploadFilePath error:nil];
and if you want to overwrite the database using the download.txt, make an instance of NSData and use - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile
Sounds like you want to get to know NSFileManager very well (documentation is linked for you).
The method you'd most likely be most interested in is:
moveItemAtPath:toPath:error:
one method could be:
you can read the file contents you want to save in NSData then can use:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile
in which you can replace the path with one your relative file paths you have mentioned for various files.

How to check if folder is empty, and instantiate file names inside the folder into NSStrings? (iphone cocoa)

Just wondering, how would I check if a particular folder is holding files, and instantiate file names inside the folder into NSStrings? I know of a class called NSFileManager, but I'm not sure how to apply it to suit my objective.
NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderLocationString error:nil];
By default all your custom files and data will be stored in the documents directory in your app. I've put a sample code below to access the default document directory; plus a custom folder you may have in there called 'MyFolderName'
The end result will be an array which has a list of NSString objects of the files or directories in the path you have specified.
//Accessing the default documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Appending the name of your custom folder, if you have any
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"MyFolderName"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) { // Directory exists
NSArray *listOfFiles = [fileManager contentsOfDirectoryAtPath:path error:nil];
}
Hope this helps! :)

Problem in getting all the files/dirs in a dir with contentsOfDirectoryAtPath

I have a zip file that I unzip it in a directory 'extract' under the Documents directory (the dir and its content is properly created). Then I would to do some stuff on each item in the new dir, dipendently if it's a file or a dir. I use the contentsOfDirectoryAtPath method of the NSFileManager.
The problem is that the array extractedItems returns always null and I don't know what I'm wronging.
NSString *dirnameForUnzippedData = [[NSString alloc] initWithString:#"extract"];
NSString *dirpath = [documentsDirectory stringByAppendingPathComponent:dirnameForUnzippedData];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *extractedItems = [fileManager contentsOfDirectoryAtPath:dirnameForUnzippedData error:NULL];
for (NSString *item in extractedItems) { ... }
It seems you are looking at the wrong path. Your code doesn't use dirpath (or your documentsDirectory).
As a side note, don't forget to release dirnameForUnzippedData after you're done with it - or just do dirnameForUnzippedData = #"extract"; instead of the alloc/init.

Saving NSMutableArray to iPhone device

In the Simulator I can save an NSMutableArray to a file and read it back with the following code:
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:#"RiskValues"]){ // If file exists open into table
NSLog(#"Risk Values File Exists");
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFileName = [NSString stringWithFormat:#"RiskValues", documentsDirectory];
gRiskValues = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
gRiskValuesAlreadyInitialised = YES;
} else {
NSLog(#"Can't find RiskValues file, so initialising gRiskValues table");
Do something else .......
}
This doesn't work on the device. I have tried to locate the file using the following but it still doesn't work:
NSString *fullFileName = [documentsDirectory stringByAppendingPathComponent#"RiskValues"];
What am I doing wrong?
Great answers from everyone. I have resolved the file path and existence issues at a stroke. Many, many thanks.
You have to provide absolute path here:
if ([fileManager fileExistsAtPath:#"RiskValues"])
So it must look like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFileName = [documentsDirectory stringByAppendingPathComponent:#"RiskValues"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: fullFileName]){ // If file exists open into table
NSLog(#"Risk Values File Exists");
gRiskValues = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
gRiskValuesAlreadyInitialised = YES;
} else {
NSLog(#"Can't find RiskValues file, so initialising gRiskValues table");
Do something else .......
}
NSString *fullFileName = [NSString stringWithFormat:#"RiskValues", documentsDirectory];
this line, you're not creating your full path string right. what you should do is
NSString *fullFileName = [documentsDirectory stringByAppendingPathComponent:#"RiskValues"];
also this check
if ([fileManager fileExistsAtPath:#"RiskValues"])
Will never pass on iOS as it is not a full path to any place you are allowed to write at in your sandbox. I suppose it works on the simulator because on the mac it's looking up relatively to the HD root (or something, not sure how the mac file system works :) ), but on the iOS you're going to have to give it a path to a file/directory in your documents (maybe by appending #"RiskValues" to it or whatever)
1) [NSString stringWithFormat:#"RiskValues", documentsDirectory] is just #"RiskValues". So this name points to file in application's directory.
2) [fileManager fileExistsAtPath:#"RiskValues"] searches for file in application directory. It's available for read/write in simulator (it's in your computer file system after all) but it's read-only on device.
BTW (NSFileManager Class Reference)
Attempting to predicate behavior based
on the current state of the file
system or a particular file on the
file system is not recommended. Doing
so can cause odd behavior in the case
of file system race conditions. It's
far better to attempt an operation
(such as loading a file or creating a
directory), check for errors, and
handle any error gracefully than it is
to try to figure out ahead of time
whether the operation will succeed.
Solution:
1) Do not check file presence. Just try to make dictionary with initWithContentsOfFile:encoding:error:
2) You want it to be in documents directory so construct path like this
[documentsDirectory stringByAppendingPathComponent:#"RiskValues"];