Get all files in Documents folder besides .DS_Store? - objective-c

I am using this code to make an array with all the documents in the Documents folder of my app... Here is the code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);'
How do I exclude .DS_Store from the array?

You can't exclude the .DS_Store files with that method, unless you want to do a second step, and filter them out of your filePathsArray. If you want to do it one step, then use contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:. You can pass nil for the properties and NSDirectoryEnumerationSkipsHiddenFiles for the options. You would also have to change the way you get path, and use URLsForDirectory:inDomains: to get the URL of the documents directory.

Will enumeratorAtURL: work for you? Here is the link http://disanji.net/iOS_Doc/#documentation/Cocoa/Conceptual/LowLevelFileMgmt/Articles/EnumADir.html

Related

Cocoa contents of directory

I have a group/folder with a series of text files. I need to get a path for each one so that I can read the contents, but I can't seem to get anything to work.
I've mucked about with [NSBundle pathsForResourcesOfType:#"txt" inDirectory:#"directoryName"] which gave me nothing but nulls or a single string that reads "Contents", [[NSFileManager defaultManager] enumeratorAtPath:#"directoryName"] which I have no idea what to do with once it's created, and [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"directoryName" error:nil].
I can't figure out what I'm doing wrong, and at this point I'm just grasping at straws. I went through 20 or 30 pages on here, none of which has really helped.
I should note that this is a Cocoa Application, not iOS.
If you want to read files in arbitrary directories, the path enumerator works nicely. A bit old fashioned, but that has its charm, too.
NSString *docPath = #"/tmp";
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:docPath];
NSString *filename;
while ((filename = [dirEnum nextObject])) {
//Do something with the file name
}
If you want to read from well-known and defined directories in your home directory, then you can use NSSearchPathForDirectoriesInDomains:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex: 0];
This will give you your Documents directory, and when used with the snippet above, list all files in that folder and subfolders.
Notice that we are not really supposed to use our nice, old Unix paths any more, but instead refer URLs.
In that case, you get something like:
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *docURL = URLs[0];
NSDirectoryEnumerator *URLEnum = [[NSFileManager defaultManager] enumeratorAtURL: docURL includingPropertiesForKeys: nil options: 0 errorHandler: nil];
NSString *filename;
while ((filename = [URLEnum nextObject])) {
// ...
}
Notice that enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: has all sorts of useful parameters, which you can read about in the docs.
Lets just take 1 of your 3:
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"directoryName" error:nil]
You should include the error parameter and check what it contains
You need to supply a full path, not just a "directoryName"
As a result you'll get an array containing the file names of the files in the directory
So if you want the full path you can do:
NSString *directoryPath = ...;
NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:...];
for(NSString *fileName in fileNames) {
NSLog(#"%#", [directoryPath stringByAppendingPathComponent:fileName]);
}
The problem was that when adding the folder, I needed to create a reference to the folder as well. Xcode does not default to this option. I had initially chosen to simply create groups, and this does not do the job.
If your group is in your current project you can use:
NSString *path = [[NSBundle mainBundle] pathForResourcesOfType:#"txt" inDirectory:#"directoryName"]
this should work for you, I noticed that you tried something similar, but make sure you're using mainBundle.

Download a file from Dropbox and save to path

I am trying to save a file from dropbox in the following way:
NSString *fileName = [NSString stringWithFormat:#"/newFile.json"];
// Do any additional setup after loading the view, typically from a nib.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path2 = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#", fileName]];
[[self restClient] loadFile:fileName intoPath:path2];
the file is under apps/appname/sandbox/newFile.json
but I get this error:
2012-05-12 21:05:46.824 Quick Homework & business[934:707] [WARNING] DropboxSDK: error making request to /1/files/sandbox/newFile.json - File not found
but the file is there!!
I found out that in order to access al dropbox folders, even if in the sandbox folder, your app needs to be set to "full dropbox access", otherwise this error comes out. this problem though is there only when trying to download from dropbox, not when uploading or when loading the metadata in a UITableView.

iPhone/iOS: How to list all files in a resource group?

I've got a bunch of resources -- images, to be specific -- which are all stuck in a resource group via XCode.
I know how to load a specific image file from within that resource group by specifying the filename and using inDirectory to specify the "path" to the group it's in.
But is it possible to obtain (programatically) a list of all the files in a certain group? The app I'm building displays a random image from among all the ones in a specific folder. While I could obviously just create a hard-coded array containing a list of all those files, it would be pretty convenient to be able to add more files just by dropping them into the folder.
So: Can it be done?
Thanks!
What about using the pathsForResourcesOfType:inDirectory: method of the NSBundle class?
It will return you a NSArray with the path of files matching the given type.
Try This:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
//---- Sorting files by extension
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF EndsWith '.png'"];
filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(#"\n\n Sorted files by extension %#",filePathsArray);

Objective-C creating a text file with a string

I'm trying to create a text file with the contents of a string to my desktop. I'm not sure if I'm doing it right, I don't get errors but it doesn't work either...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: #"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
You don't know if you're getting any errors because you're ignoring the returned YES/NO value of the -writeToFile:... method, and giving it no error pointer into which to record any possible failure. If the method returns NO, you'd check (and handle or present) the error to see what went wrong.
At a guess, the failure is due to the path you constructed. Try -stringByAppendingPathComponent: instead of -stringByAppendingString: ... this and its related methods properly handle paths.
The file probably is actually being created (ie, you might not be getting any errors after all). My guess is the file is created somewhere like "~/Desktopfile.txt" since your use of -stringByAppendingString: doesn't consider the string as slash-separated path. Check your home folder - I'll bet the file's there.
the problem is that the desktop directory string ends in nothing (no /). Check this out (on an iPhone) by using UIAlertview.

Reading data from a file

I'm new to mac and Cocoa so I'm sorry if this is a stupid question..
I need to read all the lines I wrote on a file I saved on my desktop.
The file format is .txt; I tried with stringWithContentsOfFile but the program freezes.
I tried with GDB and I noticed that, while the path is correct, the string which is supposed to contain the data returns nil.
Am I missing something important?
You need to use a path not just the filename
NSString *string;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] != 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *newFile = [documentsDirectory stringByAppendingPathComponent:#"filename.txt"];
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:newFile]) {
string = [NSString stringWithContentsOfFile:newFile];
}
}
You will need to replace the documents directory for the bundle directory if you are reading from there.
EDIT
I jumped the gun. It seems that this is NOT an iPhone question. None-the-less, you will need to pass in the full path, not just the filename