从NSData对象将图像加载到UIWebView的正确方法

从NSData对象将图像加载到UIWebView的正确方法

问题描述:

我已经将一个gif图像下载到一个NSData对象中(我已经检查了NSData对象的内容并且它已经填充了)。现在我想将该图像加载到我的UIWebView中。我尝试了以下内容:

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];

但我得到一个空白的UIWebView。直接从同一URL加载图像效果很好:

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];

我是否需要将textEncodingName设置为某些内容,或者我是否在做其他错误的操作?

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

我想手动加载图像,以便向用户报告进度,但它是一个动画gif,所以当它完成后我想在UIWebView中显示它。

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.

编辑:也许我需要以某种方式将我的图像包装在HTML中?有没有办法在不必将其保存到磁盘的情况下执行此操作?

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

我用PNG测试了代码(image / png),JPG(image / jpeg)和GIF(image / gif),它按预期工作:

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?


  • imageData不是格式良好的图像数据。尝试使用Web浏览器或图像编辑器打开文件进行检查。

  • MIME类型不正确。查看数据的第一个字节以确定实际的文件类型。

  • webView未在IB中连接,为零,为隐藏,用另一个视图覆盖,在屏幕外,有CGRectZero框架等