从文档目录ios获取文件名的文件路径 [英] Get file path by file name from documents directory ios

查看:125
本文介绍了从文档目录ios获取文件名的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我下载PDF文件,该文件存储在不同子文件夹下的Document目录中。

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.

谢谢。

推荐答案

您可以搜索文档目录,如下所示:

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

编辑:

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

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

这篇关于从文档目录ios获取文件名的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆