Get file path by file name from documents directory ios
You can search the documents directory like this:
NSString *searchFilename = @"hello.pdf"; // name of the PDF you are searching forNSArray *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 NSStringlet 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.