How to load PDFs from Documents Directory?

▼魔方 西西 提交于 2019-12-22 21:24:43

问题


I can load list of pdf files(all pdf files) from Resources folder, using this code.

 NSArray *pdfs = [[NSBundle mainBundle] pathsForResourcesOfType:@"pdf" inDirectory:nil];

But I couldn't find a method to load list of pdf files from Documents Directory. The following line of code can only load one pdf at a time.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingPathComponent:@"test.pdf"];
NSURL *urlPdf = [NSURL fileURLWithPath: file];

How could I load all pdf files from Documents Directory

Can you please give me a code example.


回答1:


I was able to solve my issue using this line of code :)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *pdfs = [[NSBundle bundleWithPath:[paths objectAtIndex:0]] pathsForResourcesOfType:@"pdf" inDirectory:nil];



回答2:


Go with NSFileManager's contentsOfDirectoryAtPath and filter the result by hand for pdf files.

This answer maybe helpful.




回答3:


You could do this

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filesAtPath = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:error];

for (NSString *path in filesAtPath) 
{
    if ([path rangeOfString:@".pdf"].length > 0)
    {
        //Do whatever you want with the pdf file
    }
}

I hope it helps, cheers



来源:https://stackoverflow.com/questions/7952930/how-to-load-pdfs-from-documents-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!