Get contents of a specific folder in documents diectory - ios

Im trying to read contents of a specific folder in documents directory thats contains only png's /Documents/ApplianceImagesFolder/
Currently I can only get all my images from documents folder, how can I target contents of ApplianceImagesFolder only?
//gets all png form documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *dir in dirContents) {
if ([dir hasSuffix:#".png"]) {
NSRange range = [dir rangeOfString:#"."];
NSString *name = [dir substringToIndex:range.location];
if (![name isEqualToString:#""]) {
[fileList addObject:name];
}
}
}
NSLog(#"document folder content list %# ",fileList);

Build the desired path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:#"ApplianceImagesFolder"];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];
And there's a better way to find the png files:
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);

Related

How to find a file in Project?

I'm getting a problem to find a file from project. I am getting this file using code but I can't get it using url.
Please help me out from this problem.
Here is the path of file
Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents/file.txt
Here is the code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *Path = [NSString stringWithFormat:#"%#/%#%#",documentsDirectory,#"file"#".txt"];
[str writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSString *fn=#"file";
NSString *searchFilename =[fn stringByAppendingString:#".txt"]; // name of the PDF you are searching for
NSArray *pathss = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorys = [pathss objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectorys];
NSString *documentsSubpath;
BOOL fileFound = false;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
fileFound=NO;
}
NSLog(#"found %#", documentsSubpath);
fileFound =YES;
}
if(fileFound){
NSLog(#"File Found");///this line is execute when i run this code
}
In code, you can use:
NSURL *fileURL = [NSURL URLWithPath: documentsSubpath];
And that will be the path to your file.
If you want to see the actual file, go to the Macintosh Finder and click "Go To Folder" (it's under the "Go" menu, or ⇧⌘G all together). Then type in your path MINUS the last path component, which is the filename. In your case, that is "/Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents".

Retrieve files from Dirrectory

My Application creates Png, Pdf, and Jpg files and stores in Documentary with different name formats. How can i retrieve all filetypes at a time. For example If i want to count how many number of pdf files in documentary, where all files exists and i have to count only pdf files. How can i achieve this for particular file types.
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger filescount = [filelist count];
NSString *filesnumber = [NSString stringWithFormat:#"%d", filescount];
NSLog(#"filesnumber:%#", filesnumber);
fileLabel.text = filesnumber;
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger filescount = 0;
for (NSString *fileName in filelist) {
if ([[fileName pathExtension] isEqualToString:#"pdf"]) {
filescount++;
}
}
NSString *filesnumber = [NSString stringWithFormat:#"%d", filescount];
NSLog(#"filesnumber:%#", filesnumber);
fileLabel.text = filesnumber;
You could || the if statement to add .jpg, .png and whatever else you may want.
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist = [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger fileCountPDF = 0;
for (NSString *fileName in filelist) {
NSString *extension = fileName.pathExtension;
if ([extension caseInsensitiveCompare:#"pdf"] == NSOrderedSame) {
NSLog(#"PDF file found");
fileCountPDF++;
}
}
NSLog(#"PDF files: %d",fileCountPDF);
//...

Filtering files in documents folder

Im currently searching my documents folder for .png images using
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);
Id like to make the search more specific, ie search for images named lorry.png, or car.png for example (for brevity) rathe rthan getting everything with .png
My image files are named by apending a reference number self.certificate.reference to the png so I get something like car283TYZ.png. This way I can utilise the correct image for the certificate that created it.
What ive tried
//search folder
NSString *certRefstring = [NSString stringWithFormat:#"%#",self.certificate.reference];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]&&[certRefstring rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound) {
NSLog(#"string does not contain cert ref %#, file list is %#",self.certificate.reference,fileList);
}
else{
NSLog(#"string contains cert ref %# and png files %#",self.certificate.reference,fileList);
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);
This seemed to return everything in the folder. So im looking for a solution for searching more specifically/iterating over my .png files in my documents folder
NSString *certRefstring = [NSString stringWithFormat:#"%#",self.certificate.reference];
so
[certRefstring rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound
is always NO. There is a reason why you receive everything.
Probably it should be changed to
[filename rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound
You should have nested 'if's
if ([fileExt isEqualToString:#"png"])
{
if ([certRefstring rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound)
{
NSLog(#"string does not contain cert ref %#, file list is %#",self.certificate.reference,fileList);
}
else
{
NSLog(#"string contains cert ref %# and png files %#",self.certificate.reference,fileList);
[fileList addObject:filename];
}
}

How to copy all text file from document directory in iOS?

I need to Copy all text files (.txt) from document directory into my folder name "Text".
I can copy only one files.
I want to copy like (*.txt) with one touch.
Here codes is my single file copy.
self.fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *cutExtension = [tblGetNameToMove.textLabel.text stringByDeletingPathExtension];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt",cutExtension]];
NSString *fileName = [NSString stringWithFormat:#"%#/Text/%#.txt",documentsDirectory,cutExtension];
[self.fileManager copyItemAtPath:txtPath toPath:fileName error:&error];
How can i do that?
Get all the contents in the folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] directoryContentsAtPath:documentsDirectory];
Enumerate over the files list and check if it constains .txt
[fileList enumerateObjectsUsingBlock:^(NSString *string, NSUInteger index, BOOL *stop) {
if ([string hasSuffix:#".txt"]) {
[[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error];
}
}];
Update
Updated my answer according to comments by Martin R
Update 2
As pointed out by Hot Licks use
if ([[string pathExtension] isEqualToString:#"txt"]) {
To check for the file extension.

How to Read a file from documents directory in iOS

I need to search a file in documents directory of iOS but i don't know the extension of that file. How to search the file without extension.
Below is the code if you know the filename.extension(abc.txt). How can i search for the same file with jsut filename(abc)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"abc.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:NULL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *fileWithExt = nil;
for (NSString *file in directoryContent )
{
if([file stringByDeletingPathExtension] isEqualsTo:#"abc"]
{
fileWithExt = file;
break;
}
}
P.S. : The fileWithExt will contain the first file with name abc

Resources