Jordy Langen
Jordy Langen

Reputation: 3591

Objective C Load PDF file in UIWebView

EDIT: There was something wrong with my Base64 decoding. I searched for a external Base64 decoder and it working just like this:

This is the case: I have a Base64 encoded byte array I get from a webservice and convert it to NSData:

NSData *data = [Base64 decodeBase64WithString:response];

And in my Webview Controller I declared:

[webview loadData:fileData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

fileData is the decoded data.

When I run this I get a gray screen. So I assume I'm not giving it a correct NSData object.

Upvotes: 6

Views: 9853

Answers (5)

Anonimys
Anonimys

Reputation: 706

UIWebView is DEPRECATED, use WKWebView https://developer.apple.com/documentation/webkit/wkwebview?language=objc

Objective-C Example:

#import <WebKit/WebKit.h>

...

CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
CGFloat height = CGRectGetHeight(screen);


WKWebView *wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
//UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width, height)]; //DEPRECATED

NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"fileName" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
//[webView loadRequest:request]; //DEPRECATED
[wkwebView loadRequest:request];

//[self.view addSubview:webView]; //DEPRECATED
[self.view addSubview:wkwebView];

Upvotes: 1

Damien Romito
Damien Romito

Reputation: 10055

The easiest way to do that:

UIWebView *webview = [[UIWebView alloc] init];
[self.view addSubview:webview];
NSString *path = [[NSBundle mainBundle] pathForResource:@"pdfFileName" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webview loadRequest:request];

Upvotes: 0

Pin
Pin

Reputation: 4016

In addition to the already provided answers, I've found that loading NSData* into a UIWebView in the initializer function of a containing UIViewController doesn't work and there'll be no error.

The NSData*needs to be loaded into the UIWebView in the viewDidLoad function.

Upvotes: 1

mdominick
mdominick

Reputation: 1319

[webView loadata:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];

That should do the trick for you, if it doesn't you can write it to a file as V1ru8 suggests, but that is an extra step in most of the cases.

Hope this will helps

Upvotes: 2

Jordy Langen
Jordy Langen

Reputation: 3591

I already answered my own question when I was typing it.

So I assume I'm not giving it a correct NSData object.

My Base64 decoding was wrong.

Using this statement works like a charm:

[webview loadData:fileData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];

I'm just posting so other people can look at it of they have the same problem.

Upvotes: 13

Related Questions