Get the list of files from document directory contains same name but with different extensions. - ios

I need to get the list of files belongs to same name .
Below are the files saved in document directory .
start.pdf , start.png , start_1.drawingpad , start_1.imagepad and other files like second.pdf , second.png .....
here .pdf , .png , .DrawingPad , .imagepad belongs to one set .
I need to list out these set , start.pdf , png , start_1.drawingpad and imagepad from document directory.

Try this,This will result the array of values which contains matched string.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *renameArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *strprdicate = [NSString stringWithFormat:#"SELF CONTAINS '%#'",#"start"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:strprdicate];
renameArray = [renameArray filteredArrayUsingPredicate:predicate];
NSLog(#"files array %#", renameArray);
Make sure you should pass input string in '' if input is a string for NSPredicate.

Related

How do i save multiple strings and not overwrite while writing to a plist file in iOS?

I'm using a "facts.plist" to display a fact(string) after pressing a button, i have a button there that writes that string to a "favourites.txt" file and there i can use it for future use.
Here is the code for that:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"MyFavorites.txt"];
//documentsDirectory];
[self.displayJoke.text writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSError *error;
NSString *str = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);
But every time I tap that button the previous string gets overwritten with the new string. How do i create a dictionary or Array to prevent this?
every time i tap that button the previous string gets overwritten with the new string
It doesn't "get overwritten". You are overwriting it:
[self.displayJoke.text writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
That line replaces the file fileName with a new file. If that's not what you want to do, then don't do that. If you want to include the existing contents of the file, it's up to you to read the file first and include that in what you write. (Alternatively, you could look into NSFileHandle, which allows you to append to a file.)

Get file path by file name from documents directory ios

In my application I download PDF files which gets stored in "Document" directory under different sub folders.
Now I have file name for which I want to get its path in "Document" directory but problem is I don't know the exact sub folder under which that file is stored.
So is there any method which will give me file path by file's name like there is one method which works for main bundle:
(NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
I don't want to iterate through each folder which is a tedious way.
Thanks.
You can search the documents directory like this:
NSString *searchFilename = #"hello.pdf"; // name of the PDF you are searching for
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSLog(#"found %#", documentsSubpath);
}
EDIT:
You can also use NSPredicate. If there are many thousands of files in the documents directory, this might crash with an out of memory error.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.lastPathComponent == %#", searchFilename];
NSArray *matchingPaths = [[[NSFileManager defaultManager] subpathsAtPath:documentsDirectory] filteredArrayUsingPredicate:predicate];
NSLog(#"%#", matchingPaths);
Swift 2.2 pretty simple:
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let plistPath = paths.stringByAppendingPathComponent("someFile.plist")
You'll have to walk the tree to find the file; there's no equivalent to -pathForResource:ofType that works in the ~/Documents directory.

How to filter file with extension from document directory in iOS?

Hello i am now retrieving file from document directory in iOS.
And also i sorted file by CreationDate.
In my document directory , it have also a lot of Folders and files.
So when i retrieve all files from document directory , that folders name are also including.
I only want to retrieve (.txt) format file.
How can i do that?
Assuming all of the files have an extension, you can create a predicate and use it to filter the array. The predicate would have a format like:
#"self ENDSWITH '.txt'"
Based on your comment below, you actually have the full file NSURL, not string file names. So you should use the predicate format:
#"absoluteString ENDSWITH '.txt'"
This is in addition to #Wain's answer and assuming that you are using a webview to load the text file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF EndsWith '.txt'"];
filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(#"files array %#", filePathsArray);
NSString *localDocumentsDirectoryVideoFilePath = [documentsDirectory
stringByAppendingPathComponent:[filePathsArray objectAtIndex:0]];
NSURL *fileUrl=[NSURL fileURLWithPath:
localDocumentsDirectoryVideoFilePath];
[_webview loadRequest:[NSURLRequest requestWithURL:fileUrl]];
Here _webview is an IBOutlet. Also, it is loading the first text file.
I hope this helps.

How to write a String in different lines to a .txt file on iOS

I am trying to write a string to a t.t file in the documents folder of my app. I can write the string to it, but when I write another string to the file it overwrites the other string, is it possible to write more strings to a text files, with a blank line between strings, many in this formate
String
String
Strine
…
I am using this code to write the string to an text file, it works for one string, but not for multible strings.
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:#"%#/Barcodedata.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = [NSString stringWithFormat:#"%#",sym.data];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
There's a few ways to do this, depending on how you implemented your code.
One way would be to load up the original .txt file into a NSMutableString object and then append that new line to the end of the string and re-write out the file (this isn't super efficient, especially as you start appending after 1000 strings, 100 strings, 50 strings, etc.)
Or you could use the low level C function "fwrite" with the append bit set.
Edited:
Since you want to see code, here's how to do it with my first suggestion:
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:#"%#/Barcodedata.txt", documentsDirectory];
//create content - four lines of text
NSError * error = NULL;
NSStringEncoding encoding;
NSMutableString * content = [[NSMutableString alloc] initWithContentsOfFile: fileName usedEncoding: &encoding error: &error];
if(content == NULL)
{
// if the file doesn't exist yet, we create a mutable string
content = [[NSMutableString alloc] init];
}
if(content)
{
[content appendFormat: #"%#", sym.data];
//save content to the documents directory
BOOL success = [content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:&error];
if(success == NO)
{
NSLog( #"couldn't write out file to %#, error is %#", fileName, [error localizedDescription]);
}
}

Content is not retrieved from file

I've got this wired problem, I cannot get the content from the file and initiate my NSMutableArray with it.
Here's my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Does file exist?: %i", [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat: #"%#/length.txt", documentsDirectory]]);
NSMutableArray *tempArr;
tempArr = [[NSMutableArray alloc] initWithContentsOfFile:[NSString stringWithFormat: #"%#/length.txt", documentsDirectory]];
When trying this, initWithContentsOfFile returns (null). The row checking if the file exist prints '1' to the console.
This is the code I'm using to save the data:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[length.text writeToFile:[NSString stringWithFormat: #"%#/length.txt", documentsDirectory] atomically:NO];
I'm using more or less exactly the same code in a different program without problems.
Really need some help here, perhaps I'm just blind for the moment...
When you try to create an array from the contents of a file, the file must be in plist format, and the outer-most plist element must be <array>. If it doesn't have that format, initialization will fail and your array will be nil.
You're creating the file by writing an NSString to a file, which means you should probably be reading it in to an NSString, not an NSArray.
The docs for NSArray's initWithContentsOfFile: method say:
Return Value An array initialized to contain the contents of the file
specified by aPath or nil if the file
can’t be opened or the contents of the
file can’t be parsed into an array.
The returned object might be different
than the original receiver.
You don't include the declaration of length in your code snippet, but I'm guessing that length.text returns an NSString object, not an NSArray. So you'd need to read that back from a file using initWithContentsOfFile: from NSString, not NSArray.

Resources