Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS QLPreviewController show pdf saved to file system

I have QLPreviewController working if I show a PDF file system from my bundle on the project,

like this example

but If I want to show a PDF from the file system, it doesnt show it, how can I call a pdf file that I have just downloaded in my file system?

The code:

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

}

So my problem is how to get the pdf [only pdf in the documents directory], how do i get this pdf?

thanks

thanks!

like image 919
manuelBetancurt Avatar asked Mar 23 '23 18:03

manuelBetancurt


1 Answers

Change your init method to below.

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

Add this new method

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

And replace your method with my method

- (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];
}

Code is self explanatory. Just create the array of all the documents that are in your document directory. And after that use that array to create the path and provide URL of that path to QLPreviewController

like image 187
Iducool Avatar answered May 07 '23 08:05

Iducool