iOS QLPreviewController显示保存到文件系统的pdf

时间:2013-08-16 04:17:05

标签: ios qlpreviewcontroller

如果我在项目的包中显示PDF文件系统,我有QLPreviewController工作,

像这样example

但如果我想从文件系统中显示PDF,它没有显示它,我怎样才能调用我刚刚在我的文件系统中下载的pdf文件?

代码:

- (void)initPDFviewer
{
    QLPreviewController *previewController=[[QLPreviewController alloc]init];
    previewController.delegate=self;
    previewController.dataSource=self;
    [self presentModalViewController:previewController animated:YES];
    [previewController.navigationItem setRightBarButtonItem:nil];
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    //return 0;


    //return url!


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSLog(@"paths :: %@", paths);

    return 0;

}

所以我的问题是如何获取pdf [仅在文档目录中的pdf],我如何获得这个pdf?

感谢

谢谢!

2 个答案:

答案 0 :(得分:6)

将您的init方法更改为以下。

-(id)init
{
    if (self = [super init])
    {
        //  arrayOfDocuments = [[NSArray alloc] initWithObjects: 
        //          @"iOSDevTips.png", @"Remodel.xls", @"Core J2ME Technology.pdf", nil];

         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
         NSString *docPath = [paths lastObject];

         NSArray *docArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docPath error:nil];

         arrayOfDocuments = [[NSArray alloc] initWithArray:docArray];
    }
    return self;
}

添加此新方法

-(NSString*)documentDirectoryPathForResource:(NSString*)aFileName 
{
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
     NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:aFileName];
     return fullPath;
}

用我的方法替换你的方法

- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index 
{
      // Break the path into it's components (filename and extension)
      NSString *path = [self documentDirectoryPathForResource:arrayOfDocuments[index]];

      return [NSURL fileURLWithPath:path];
}

代码是不言自明的。只需创建文档目录中所有文档的数组即可。然后使用该数组创建路径并提供该路径的URL到QLPreviewController

答案 1 :(得分:1)

NSURL *fileURL = nil;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *wordFilePath = [documentsDirectory stringByAppendingPathComponent:@"sample.doc"];

fileURL = [NSURL fileURLWithPath:wordFilePath];

return fileURL;