iOS copy directories including subdirectories - iphone

I am working with iOS document folder called "temp" that allocates subdirectories that contain files dowloaded from remote url. Now I need to copy "temp" directory and all its contents to "main" folder (overwrite existing that was previously created). I know how to handle files but how to copy whole directory? Thank you

You can use the same NSFileManager methods that you know and love for directories as well. For example:
if ([[NSFileManager defaultManager] fileExistsAtPath:pathToTempDirectoryInMain]) {
[[NSFileManager defaultManager] removeItemAtPath:pathToTempDirectoryInMain error:nil];
}
NSError *copyError = nil;
if (![[NSFileManager defaultManager] copyItemAtPath:pathToTempDirectory toPath:pathToTempDirectoryInMain error:&copyError]) {
NSLog(#"Error copying files: %#", [copyError localizedDescription]);
}

The NSFileManager methods removeItemAtPath:error:, removeItemAtURL:error:, copyItemAtPath:toPath:error:, and copyItemAtURL:toURL:error: methods handle directories.
You might also look at moveItemAtPath:toPath:error: and moveItemAtURL:toURL:error:.

Related

iOS File won't write to directory

I'm using cocoaHTTPServer library that allows you to store files "publicly". For some reason I can't write files to the directory.
I can write to my local file directory, but not the public "Web" folder.
/var/mobile/Applications/42CE308A-F804-47E3-BA07-CB921B909FFB/Documents/song.caf
/var/mobile/Applications/42CE308A-F804-47E3-BA07-CB921B909FFB/MyApp.app/Web/song.caf
The top one works, the bottom one doesn't.
Meaning, when I save the file, then check for the file in the documents directory, it is there, when I save, and then check the "Web" directory, the directory is empty.
And i'm using AVAssetWriter to save the song.
NSString *exportPath = [DataCenter sharedDataCenter].songURLLocal;
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:exportURL
fileType:AVFileTypeCoreAudioFormat
error:&assetError];
What does the assetError output through NSLog?
Also, You will not be able to write the the Web directory which is clearly located in your app bundle — which is sandboxed. The only directory you can write to is the Documents directory.
Also, what is the NSString *exportPath = [DataCenter sharedDataCenter].songURLLocal?
If exportPath is the Web directory then your methods will always fail.

How to download file and save in local iphone application?

I have locally saved one xml file and showing the details by using NSXmlParser(Which is stored in Resource folder). But, now i want to download new xml from url(from client side) and need to store that new xml file in local and also need to delete existing one from the application. How can i do this? Any suggestions? There is any sample code/project for reference? Please help me. Thanks for reading my poor english. Thanks is advance.
although u can delete file from yr resource directory and save new one but the my way is to perform file operation mostly on app diretories like document directory or cache directory.
first u will to save yr xml file from app resource to cache directory then access file from there.And u can also remove file from resource directory ,its no longer needed.
any new file available in internet then first remove old one from cache and add new one to cache directory.
whole thing is as follows:-
//get your cachedirectory path
NSArray *imagepaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachdirectory = [[NSString alloc] initWithString:[imagepaths objectAtIndex:0]];
//first save your file from resource directory to app's cache directory
NSString * path = [[NSBundle mainBundle] pathForResource:#"fileinresource" ofType:#"xml"];
NSData *filedata = [NSData dataWithContentsOfFile:path];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *savename = [cachdirectory stringByAppendingPathComponent:#"mynewfile.xml"];
[fileManager createFileAtPath:savename contents:filedata attributes:nil];
//remove file from resource directory
[fileManager removeItemAtPath:path error:nil];
//new file from internet is avilable then do following:first remove old file from cache
[fileManager removeItemAtPath:cachdirectory error:nil];
//save new file from internet
NSData *newfiledata=[NSData dataWithContentsOfURL:[NSURL URLWithString:myxmlurlstringpath]];
[fileManager createFileAtPath:savename contents:newfiledata attributes:nil];

Is possible to read plist from application bundle and documents folder at the same time?

Is it possible?to read from my local bundle and at the same time also read from documents folder into UItableview?
thanks thanks
yes.simultaneously
No — as in the iPhone isn't multicore, you can't have "simultaneous" :p
Yes — as in you can open multiple files in the same period of time. There's no conflicts as long as the files are different (if the files are the same then it depends on how others are using and locking the file etc.)
on viewDidLoad or some similar event when you would be populating your table data, you would simply just aggregate the two files together... that is you are are likely populating an array or dictionary with the contents of the file in question... so use the mutable version of array/dictionary, initialize it empty, then read in the first file from whatever location you choose, populating into your mutable array/dictionary, then do the the same for the next file. after you are done, reloadData as you normally would as if you had read form one file.
As far as simultaneous goes, technically no. However, one could have two different active threads each one reading required files and parsing the data.
Regarding the files you want to access...
Here is a quick and dirty method I use in one project (which I just happen to be working on at the moment):
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError* error;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
self.blahDBPath = [self.documentsDirectory stringByAppendingPathComponent: #"blah.db"];
NSLog(#"Mainbundle Resourcepath: %#", [[NSBundle mainBundle] resourcePath]);
NSString* defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"blah.db"];
NSLog(#"Default DB Path: %#", defaultDBPath);
success = [fileManager copyItemAtPath:defaultDBPath toPath:self.blahDBPath error:&error];
if (!success) {
NSAssert1(0, #"blah blah blah '%#'.", [error localizedDescription]);
}
It is ugly but effective. I'll rewrite it when I refactor the application.
The point here is that I ask the operating system for the path to certain directories. Then I add file names or subdirectories as required. This allows the operating system to manage paths (like in the simulator where each successive build gets a new unique id as part of its path) and I just worry about the final directories and file names in the application.
One I have the paths, I copy the required file from the bundle directory and put them somewhere, the Documents directory in this case. Then I can do whatever I need to with them.
If I just wanted to access them as they are in the bundle directory, then I I just refer to them by using [[NSBundle mainBundle] resourcePath].
I think something along the lines of the above snippet is what you are looking for.
-isdi-

iphone storing and then reading a file from Documents folder

this must be easy but I want to put a file in the Documents folder which is read in at start up. I have the code on how to read and have confirmed its looking in the correct directory. However the file I have ,RootList.txt when saved in the Resources folder in xcode, is stored under the Root.app folder and the Documents folder is empty. Therefore its not finding this file when I start the app.
Is there a way to ensure a file is built into the Documents directory at start up (I'm running this in the simulator).
The alternative is a plist which works fine as well but I'm just curious.
In these situations I follow this approach:
First save your RootList.txt in Resources folder in xCode.You have nothing in your Documents folder, yet.
In the beginning of your applicationDidLaunch call, do:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:#"RootList.txt"];
if(![fileManager fileExistsAtPath:path])
{
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/RootList.txt"]];
[data writeToFile:path atomically:YES];
}
Now, your file is in Documents folder at startup.

Deleting non-empty folders and specific file types

What is the best way to remove a folder, deleting all subfolders and files?
What is the best way to remove files with a specific extension; e.g., if I want to remove only files with '.txt' extension?
Cocoa or carbon.
To remove a directory tree (or file), use -[NSFileManager removeItemAtPath:error:]. This deletes the files directly (and it will delete all of them); if you want to move the item to the Trash instead, use NSWorkspaceRecycleOperation .
As for removing only files with specific extensions: Get each pathname's pathExtension and use caseInsensitiveCompare: to compare it to the ones you're looking for, then remove the file if it's on your hit list.
If you want to combine the two (i.e., remove only files within a directory tree that have a given extension), you'll need to get a directory enumerator from the NSFileManager and walk the directory tree yourself, removing files one by one.
Yep, be sure to use therecycle bin unless of course they are files the user shouldn't see/know about.
To remove files with specific extension..
One way at least.. This example is just looking in the application documents directory for any files with the extension jpg and removing them..
NSFileManager *fManager = [NSFileManager defaultManager];
NSString *dir = [self applicationDocumentsDirectory];
NSError *error;
NSArray *files = [fManager contentsOfDirectoryAtPath:dir error:&error];
for (NSString *file in files) {
if ([[[file pathExtension] lowercaseString] isEqualToString: #"jpg"])
{
[fManager removeItemAtPath: [dirstringByAppendingPathComponent:file] error:&error];
NSLog(#"removed: %#",file);
}
if (error) {
//deal with it
}
}