Correct way to load image into UIWebView from NSData object

rustyshelf picture rustyshelf · May 13, 2010 · Viewed 31.3k times · Source

I have downloaded a gif image into an NSData object (I've checked the contents of the NSData object and it's definitely populated). Now I want to load that image into my UIWebView. I've tried the following:

[webView loadData:imageData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

but I get a blank UIWebView. Loading the image from the same URL directly works fine:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
[imageView loadRequest:request];

Do I need to set the textEncodingName to something, or am I doing something else wrong?

I want to load the image manually so I can report progress to the user, but it's an animated gif, so when it's done I want to show it in a UIWebView.

Edit: Perhaps I need to wrap my image in HTML somehow? Is there a way to do this without having to save it to disk?

Answer

Costique picture Costique · Feb 5, 2011

I tested the code with PNG ("image/png"), JPG ("image/jpeg") and GIF ("image/gif"), and it works as expected:

[webView loadData:imageData MIMEType:imageMIMEType textEncodingName:nil baseURL:nil];

Now, what's wrong with your app?

  • the imageData is not a well-formed image data. Try opening the file with a web browser or an image editor to check it.
  • the MIME type is incorrect. Look at the first bytes of the data to determine the actual file type.
  • webView is not connected in IB, is nil, is hidden, is covered with another view, is off screen, has a CGRectZero frame, etc.