Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
943 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...