Get file path by file name from documents directory ios

ViruMax picture ViruMax · May 21, 2014 · Viewed 31.8k times · Source

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.

Answer

Abhi Beckert picture Abhi Beckert · May 21, 2014

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);