Get file path by file name from documents directory ios - 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.

Related

Cleared the files but memory is not reduced

I am creating an application. I am storing the files in Document directory. And after my work completed, delete the files from document directory as like below:
NSMutableDictionary * Dictionary = [NSMutableDictionary alloc]init];
// Next every file storing into this dictionary like below
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *baseDir = [paths objectAtIndex:0];
NSString *pathComp = [baseDir stringByAppendingPathComponent:[NSString stringWithFormat:#"IMG%d.PNG",presentCount];
fileURL = [NSURL fileURLWithPath:pathComp];
[Dictionary setObject:fileURL forKey:fileURL];
while ([[Dictionary allKeys]count]!=0) {
NSURL *deleteFileURL = [[Dictionary allKeys] lastObject];
NSLog(#"Path %#",deleteFileURL.path);
[[NSFileManager defaultManager] removeItemAtPath:deleteFileURL.path error:nil];
[Dictionary removeObjectForKey:deleteFileURL];
}
Here my problem is, after delete the files from document directory, memory is not reduced, still it's occupying as like files exist. Due to this issue, my is crashing. So please help me how to clear the memory.
Actually i am getting the files(Photos ) from the server and first placing in documents directory,and trying to save using photo library.Once i give input from dictionary to photo library, after completion handler, i am trying to delete the file.Its removed and photo saved, but memory is not reduced.
1、Remove the file after checking for the existence of a file on the path, and check the return value of removeItemAtPath: to determine if the deletion succeeded.
NSString *path = #"a/b";
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
// Check the success's value
}

Reading and Writing NSMutableArray to iPhone not working (Works on iOS Simulator)

In an app I am working on I want to have an NSMutableArray (called pathsArray) that I can read from a file in the app's directory, be able create an instance of that array that I can add objects to and/or remove objects from, and then I want to write it back to the file. I have a UILabel that shows the number of contents in this array. My problem: my code below works fine on Xcode's iOS Simulator but when I try to run the app on my actual iPhone the data isn't saved. I know there are a lot of questions on here related to this issue but i can't seem to see what I am doing wrong. Any help would be greatly appreciated.
- (void) loadArrayContents {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingString:#"theArray"];
//Objects contained in an array returned by 'initWithContentsOfFile' are immutable even if the array is mutable
NSArray* contentsArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
pathsArray = [[NSMutableArray alloc] initWithArray:contentsArray];
}
and...
- (void) saveArrayContents {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingString:#"theArray"];
[pathsArray writeToFile:filePath atomically:YES]);
}
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"theArray"];
should solve the issue. The problem with
NSString *filePath = [documentsDirectory stringByAppendingString:#"theArray"];
is that it does not add / in the file path.

Listing files from specific documents directory folder

I have saved many files in a folder in the documents directory. This is the path to one of them:
/var/mobile/Applications/120FD973-C902-405E-A645-B1651904CE9B/Documents/1127029/BusinessCard2258009241.card
I want to list the files in the folder (1127029), and I tried this:
NSFileManager *fManager = [NSFileManager defaultManager];
NSString *item;
NSArray *contents = [fManager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%d", FolderNumber]] error:nil];
// >>> this section here adds all files with the chosen extension to an array
for (item in contents){
if ([[item pathExtension] isEqualToString:#"card"]) {
...
But it doesn't work
Don't try to get to the documents directory that way. It won't work. Use this code fragment instead:
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Then use stringByAppendingPathComponent: to add the subdirectory name.

Why can't I retrieve my plist file?

I have a plist file I just created of strings; it looks like this:
This is the code I'm using to create the path to the file:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // Create a list of paths
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get a path to your documents directory from the list
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"NailServices.plist"]; // Create a full file path
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) { // Check if file exists
// Get a path to the plist created before in bundle directory (by Xcode)
NSString *bundle = [[NSBundle mainBundle] pathForResource: #"NailServices" ofType: #"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error]; // Copy this plist to your documents directory
}
This is the code I'm using to examine the data (to make sure this is working)... I'm getting a (null) back from the NSLog statement)
//Load Dictionary with wood name cross refference values for image name
NSString *plistDataPath = [[NSBundle mainBundle] pathForResource:#"NailServices" ofType:#"plist"];
NSDictionary *NailServicesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistDataPath];
NSLog(#"\nnailServicesDict: %#", NailServicesDictionary);
This is my first attempt at creating/using a "strings" plist file; I have read everything I could find on Google and SO without finding an example of a plain ol' strings file. What else do I have to do to be able to get to this plist data?
Your problem is that you are creating an NSDictionary while your plist is an NSArray. Thus, it will return nil when you try to create it as a dictionary because no dictionary exists.
You need to change:
NSDictionary *NailServicesDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistDataPath];
to
NSArray *NailServicesArray = [[NSArray alloc] initWithContentsOfFile:plistDataPath];
As a commenter posted, plist files can either have an NSArray or an NSDictionary as their root. Your example plist has an NSArray as its root, so you'll want to alloc and init an NSArray, not an NSDictionary. If your plist is stored in the app bundle when you build the app in Xcode and you don't need to modify it at runtime, then it's unnecessary to copy it to the NSDocumentsDirectory. Also, I'd recommend using [paths lastObject]; rather than [paths objectAtIndex:0];, which can throw an exception if the paths array is empty.

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.

Resources