ios 从文档目录ios中按文件名获取文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23780928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:10:30  来源:igfitidea点击:

Get file path by file name from documents directory ios

iosobjective-cnsfilemanagernsbundle

提问by ViruMax

In my application I download PDF files which gets stored in "Document" directory under different sub folders.

在我的应用程序中,我下载了存储在不同子文件夹下的“文档”目录中的 PDF 文件。

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 namelike 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.

谢谢。

回答by Abhi Beckert

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.

您也可以使用 NSPredicate。如果文档目录中有数千个文件,这可能会因内存不足错误而崩溃。

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.lastPathComponent == %@", searchFilename];
NSArray *matchingPaths = [[[NSFileManager defaultManager] subpathsAtPath:documentsDirectory] filteredArrayUsingPredicate:predicate];

NSLog(@"%@", matchingPaths);

回答by FreeGor

Swift 2.2 pretty simple:

Swift 2.2 非常简单:

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
let plistPath = paths.stringByAppendingPathComponent("someFile.plist")

回答by Ben Gottlieb

You'll have to walk the tree to find the file; there's no equivalent to -pathForResource:ofType that works in the ~/Documents directory.

您必须遍历树才能找到文件;没有等效于 -pathForResource:ofType 在 ~/Documents 目录中工作的内容。