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