Mark Reid
Mark Reid

Reputation: 2641

Loading a local image directly into a UIWebView without HTML?

I'm trying to load a local image file into a UIWebView. Is it necessary to create an HTML file and load the image into it or can I directly load the image in a web view?

This is the code I'm using currently to load the image into the web view, but it shows up blank.

NSURL *url = [NSURL fileURLWithPath:localFilePath isDirectory:NO];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

Upvotes: 1

Views: 1346

Answers (2)

Chris Loonam
Chris Loonam

Reputation: 5745

UIWebView has a loadData:MIMEType:textEncodingName:baseURL: method. Rather than writing HTML with the image in it, you could do something simpler like this

NSData *imageData = [NSData dataWithContentsOfURL:fileURL];
[self.webView loadData:imageData MIMEType:@"image/..." textEncodingName:@"utf-8" baseURL:nil];

the MIMEType argument should be changed to whatever MIME type the image is. (e.g. jpeg is image/jpeg)

Upvotes: 2

josefdlange
josefdlange

Reputation: 453

Why are you trying to load an image into a UIWebView? That seems like a waste to me. That being said, I'd honestly say that the easiest way to do what you're trying to accomplish is to add a UIImageView as a subview of that web view.

You could also do this, I think, if you wanted to inject an HTML string referencing an image stored in your bundle:

// Given a UIWebView property called webView, and
// an image named "foo.png" in your main bundle.
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *bundlePathURL = [NSURL fileURLWithPath:bundlePath];
[webView loadHTMLString:@"<img src=\"foo.png\" />" baseURL:bundlePathURL]; // Where foo.png is at that path, hopefully.

Upvotes: 0

Related Questions