I want to add a list of Files in Document Directory to an Array of Strings. Not sure exactly how to do this, this is what I have so far. I want to load/store only the files that contain the word 'bottom' in the filename in the array. How do i do this exactly?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileMan = [[NSFileManager alloc]init];
NSArray *files = [fileMan contentsOfDirectoryAtPath:documentsDirectory error:nil];
for(int i =0; i<files.count; i++){
}
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString rangeOfString:#"bottom"]];
//THIS IS HARDCODED ARRAY OF FILE-STRING NAMES
NSArray *bottomArray =[NSArray arrayWithObjects: #"bottom6D08B918-326D-41E1-8A47-B92F80EF07E5-1240-000005EB14009605.png", #"bottom837C95CF-85B2-456D-8197-326A637F3A5B-6021-0000340042C31C23.png", nil];
You need to check each file in the files array:
NSFileManager *fileMan = [NSFileManager defaultFileManager];
NSArray *files = [fileMan contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *bottomArray = [NSMutableArray array];
for (NSString *file in files) {
if ([file rangeOfString:#"bottom"].location != NSNotFound) {
[bottomArray addObject:file];
}
}
In addition to #rmaddy's approach, another option is to use an instance of NSPredicate to filter the array of file names:
NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self contains 'bottom'"];
NSArray *matchedNames = [filenames filteredArrayUsingPredicate:predicate];
Related
I am trying to use NSFileManager to move a file from the Documents/Inbox folder to the Documents folder. I used breakpoints to figure out where my code wasn't working, and everything seemed to be running fine until it hit the part where it actually moves the files. The directories are found and the files are noted in the debugger, but it just won't move. Here is my entire viewDidLoad method (there's nothing in [super viewDidLoad];):
//Turn every file inside the directory into an array
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appFolderPath = [path objectAtIndex:0];
NSString *inboxAppFolderPath = [appFolderPath stringByAppendingString:#"/Inbox"]; //changes the directory address to make it for the inbox
//NSPredicates to filter out files I don't want in my NSArray
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"not SELF beginswith[c] '.DS_Store'"];
NSPredicate *inboxPredicate = [NSPredicate predicateWithFormat:#"not SELF beginswith[c] 'Inbox'"];
recipes = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appFolderPath error:nil];
recipes = [recipes filteredArrayUsingPredicate:predicate];
recipes = [recipes filteredArrayUsingPredicate:inboxPredicate];
//get to inbox directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:inboxAppFolderPath,documentsDirectory] error:nil];
//move all the files over
for (int i = 0; i != [inboxContents count]; i++)
{
NSString *oldPath = [NSString stringWithFormat:inboxAppFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
NSString *newPath = [NSString stringWithFormat:appFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
}
There may be issue for creating sub folder inside Documents.
Try to create inboxAppFolder in this manner.
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *inboxAppFolderPath = [path stringByAppendingPathComponent:#"Inbox"]; // subDirectory
if (![[NSFileManager defaultManager] fileExistsAtPath: inboxAppFolderPath])
[[NSFileManager defaultManager] createDirectoryAtPath: inboxAppFolderPath withIntermediateDirectories:NO attributes:nil error:nil];
//Rest of your code
Hope, it'll help you.
Thanks.
Here is kind of an overview of what I'm trying to do. My app has a form on it, and the form data is saved as a .csv file in the documents directory. I want to parse through the documents directory and get the filenames of the files that are .csv files. I then want to display these filenames in a UITableView so that the user can choose a file to be attached to the email. I'm having some trouble getting the filenames into an NSMutableArray. Below is my code:
NSString *extension = #"csv";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error = nil;
NSArray *documentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
NSLog(#"files array %#", documentArray);
NSString *filename;
for (filename in documentArray) {
if ([[filename pathExtension] isEqualToString:extension])
{
[_mySingleton.filePathsArray addObject:filename];
}
}
NSLog(#"files array %#", _mySingleton.filePathsArray);
The first NSlog returns what looks to be all the filenames in the folder. In the second NSlog it should only be printing the .csv filenames, instead it is returning null. Obviously that code in the for loop is not working, how can I fix this? Also I hope it is not confusing, I have a singleton class and in this case I'm storing the filenames in it so that they can be edited and accessed across multiple views.
Thanks,
Alex
try to use built in a filter function
NSArray *files = #[#"11.csv", #"22.txt", #"333.csv", #"444.doc"];
NSArray *cvsFiles = [files filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject hasSuffix:#".csv"];
}]];
NSLog(#"%#", cvsFiles);
And in your code the filePathsArray will have only names of files. You should append a directory path to.
[_mySingleton.filePathsArray addObject:[documentsDirectory stringByAppendingPathComponent:filename];
full version
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *documentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSArray *cvsFiles = [documentArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject hasSuffix:#".csv"];
}]];
NSMutableArray *filePaths = [#[] mutableCopy];
for (NSString *fileName in cvsFiles) {
[filePaths addObject:[documentsDirectory stringByAppendingPathComponent:fileName]];
}
_mySingleton.filePathsArray = filePaths
You wrote
In the second NSlog it should only be printing the .csv filenames,
instead it is returning null.
It means that _mySingleton.filePathsArray is not initialised. In case it will be initialised NSLog will print an empty array, not null.
What you have to do - add _mySingleton.filePathsArray initialisation somewhere before it is used:
_mySingleton.filePathsArray = [NSMutableArray new];
I am writing data to plist with always returns me the nil value.. I have to append data also to the previous values of array. But Values are always null..
Below is the code:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"a.plist"];
// set the variables to the values in the text fields
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:#"c" forKey:#"Id"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
[array addObject:plistDict];
[array writeToFile:plistPath atomically:YES];
NSLog(#"array%#",array);
}
else
{
NSArray *array = [NSArray arrayWithObject:plistPath];
[array writeToFile:plistPath atomically:YES];
}
If I understand your question correctly, I tested the code with just one little change i.e, Added array declaration and it's working fine. Please pardon me if this is not the issue.
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"a.plist"];
// set the variables to the values in the text fields
NSMutableArray *array;
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:#"c" forKey:#"Id"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
[array addObject:plistDict];
[array writeToFile:plistPath atomically:YES];
NSLog(#"array%#",array);
}
else
{
NSArray *array = [NSArray arrayWithObject:plistPath];
[array writeToFile:plistPath atomically:YES];
}
I have a .plist file which have this structure,
I want to add or replace the Item 5. I am using this code
NSError *error ;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Introduction.plist"];
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSString *comment = str;
[data replaceObjectAtIndex:1 withObject:comment];
[data writeToFile:path atomically:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Introduction" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
If I change replaceObjectAtIndex: to 5 it changes my plist structure, and I don't want that.
How can I insert/replace the text at the row 5 (Item 5) of particular Index?
You structure has an array of arrays.
[data replaceObjectAtIndex:1 withObject:comment];
By this code you are replacing an array at index 1 with a string. Do you specifically need to insert to 5th index or do you just need to add it to existing sub array?
NSMutableArray *subArray = [data[sectionIndex] mutableCopy];
if (!subArray) {
subArray = [NSMutableArray array];
}
if (rowIndex<[subArray count]) {
[subArray replaceObjectAtIndex:rowIndex withObject:comment];
}else{
[subArray addObject:comment];
}
[data replaceObjectAtIndex:sectionIndex withObject:subArray];
[data writeToFile:path atomically:NO];
Access the subArray, make it mutable and add or insert at specific index. If you are trying to insert don't forget to include a check if the index is not greater than count of that array.
Working in iOS 5 I have read a list of file names from my documents directory the array is called "file list". I am trying to get a list of file names without extensions. Only the last name in my list has the extension removed. Any ideas?
- (IBAction)getFile:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory =[paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *names = [[[fileList valueForKey:#"description"]componentsJoinedByString:#"\n"]stringByDeletingPathExtension];
NSLog(#"File Name Is \n%#",names);
showFile.text = names;
}
- (IBAction)getFile:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory =[paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *names = nil;
for (NSString *name in fileList){
if (!names) names = [[name lastPathComponent] stringByDeletingPathExtension];
else names = [names stringByAppendingFormat:#" %#",[[name lastPathComponent] stringByDeletingPathExtension]];
}
NSLog(#"File Name Is \n%#",names
}
Looks like you are using the description of the array to get the full array contents, and then you are removing the file extension for the whole thing rather than from each individual file. Try removing the filename extensions first:
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[fileList count]];
[fileList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[newArray addObject:[obj stringByDeletingPathExtension]];
}];
NSString *names = [newArray componentsJoinedByString:#"\n"];
showFile.text = names;
The enumerateObjectsUsingBock method goes through each item in the array. In the code block you take that object, delete the path extension, and add it to a new array. After the full array has been processed, you can them use componentsJoinedByString to add the newline between each filename.