IOS QLPreviewController show pdf saved in file system

QLPreviewController works for me if I show the PDF file system from my package in a project,

as an example

but if I want to show a PDF file from the file system, it will not show it, how can I call the pdf file that I just uploaded to 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 pdf [only pdf in the docs directory], how can I get this pdf?

thanks

thanks!

+4
source share
2 answers

Change the init method 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 components (filename and extension) NSString *path = [self documentDirectoryPathForResource:arrayOfDocuments[index]]; return [NSURL fileURLWithPath:path]; } 

The code itself. Just create an array of all the documents that are in your document directory. And after that, use this array to create the path and specify the URL of this path for the QLPreviewController

+6
source
 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; 
+1
source

Source: https://habr.com/ru/post/1497361/


All Articles