Jansen82
Jansen82

Reputation: 25

Show downloaded PDF file with webView ios

I'm making an iPhone app, that will download a PDF file and display it in a webView. However my script will not show the downloaded PDF. It does download it and save it in Documents, but the webView will not show it.

Here's my script:

NSString *path = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"pdf"];
NSURL *urlen = [NSURL fileURLWithPath:path];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:urlen];
[webView loadRequest:urlRequest];
[webView setScalesPageToFit:YES];

Upvotes: 2

Views: 1368

Answers (1)

nhgrif
nhgrif

Reputation: 62072

From the official documentation on NSURL official documentation on NSURL.

Sending nil as the argument to fileURLWithPath: produces an exception.

The problem then is actually with [[NSBundle mainBundle] pathForResource:ofType:]. This is returning nil, rather than an actual path to a file.

The problem here is actually that [NSBundle mainBundle] refers to files that are bundle with your app. You need to look in your app's document directory, which is where it stores files it has downloaded.

This method will give you the path to your app's document directory:

NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

Now, just append the file name to this path:

NSString *pdfPath = [documentsPath stringByAppendingPathComponent:@"3.pdf"];

And for good measure (because crashes are always bad), make sure the file exists as such:

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pdfPath];

And finish as such:

if (fileExists) {
    NSURL *urlen = [NSURL fileURLWithPath:pdfPath];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:urlen];
    [webView loadRequest:urlRequest];
    [webView setScalesPageToFit:YES];
} else {
    // probably let the user know there's some sort of problem
}

Upvotes: 2

Related Questions