Anthony
Anthony

Reputation: 2801

How to store a pdf file loaded into an UIWebView in my Documents directory?

Currently, I detect if the UIWebView load a pdf file by doing a check on the current URL. Next I download the pdf file with ASIHTTPRequest library. The problem is that if the file is display in the UIWebView, is that it is already downloaded somewhere, so I download this file twice. How can I get this file load in my UIWebView ?

The purpose is to store this file loaded in my UIWebView in my Document directory.

Upvotes: 1

Views: 2129

Answers (2)

Samir Jwarchan
Samir Jwarchan

Reputation: 1027

Here's how you can download, read and store your pdf locally in iphone application, so that you don't have to download regularly:

First create UIWebView and include <<UIWebViewDelegate>>

  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
  NSString *documentsPath = [paths objectAtIndex:0];
  NSString *filePath = [documentsPath stringByAppendingPathComponent:@"YourPDF.pdf"]; 
 if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){ // if file not present
           // download file , here "https://s3.amazonaws.com/hgjgj.pdf" = pdf downloading link
         NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"https://s3.amazonaws.com/hgjgj.pdf"]];
            //Store the downloaded file  in documents directory as a NSData format
         [pdfData writeToFile:filePath atomically:YES];
    }

     NSURL *url = [NSURL fileURLWithPath:filePath];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     [yourWebView setUserInteractionEnabled:YES];
     [yourWebView setDelegate:self];
     yourWebView.scalesPageToFit = YES;
     [yourWebView loadRequest:requestObj];

Or, if you simply want to read/load pdf from your Resource folder then simply do this :

     NSString*  filePath= [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"pdf"]];
    /// or you can even read docs file as : pathForResource:@"sample" ofType:@"docx"]
     NSURL *url = [NSURL fileURLWithPath:filePath];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     [yourWebView setUserInteractionEnabled:YES];
     [yourWebView setDelegate:self];
     yourWebView.scalesPageToFit = YES;
     [yourWebView loadRequest:requestObj];

Upvotes: 1

Uko
Uko

Reputation: 13386

All I can suggest is either to download it a second time, or put it in the temporal storage and then put it it the UIWebView and when the user asks, then put it where you want from the temporal storage.

Upvotes: 0

Related Questions