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

时间:2010-05-13 15:13:13

标签: iphone uiwebview nsdata

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

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

但我得到一个空白的UIWebView。直接从相同的URL加载图像可以正常工作:

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

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

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

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

10 个答案:

答案 0 :(得分:23)

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

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

现在,你的应用程序出了什么问题?

  • imageData不是格式良好的图像数据。尝试使用Web浏览器或图像编辑器打开文件进行检查。
  • MIME类型不正确。查看数据的第一个字节以确定实际的文件类型。
  • webView未连接IB,为零,隐藏,被其他视图覆盖,关闭屏幕,有CGRectZero框架等。

答案 1 :(得分:6)

我并没有真正尝试将图片加载到UIWebView,但谷歌搜索给了我。我认为你的图片字符串必须有一个好的路径,看起来像一个URL

NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString *HTMLData = @"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:@"file:/%@//",imagePath]]];

您可以在此处查看更多详细信息:Loading local files to UIWebView

答案 2 :(得分:4)

UIImage *screenshot= [UIImage imageAtPath:
                              [[NSBundle mainBundle] pathForResource:@"MfLogo_aboutus" ofType:@"png"]]; 
NSData *myData = UIImagePNGRepresentation(screenshot); 
[vc addAttachmentData:myData mimeType:@"image/png" fileName:@"logo.png"];

答案 3 :(得分:3)

您可以将urlImage加载到未在本地保存的webview中,如下面的代码

所示
NSString *str = @"";
        str = [str stringByAppendingString:@"http://t3.gstatic.com/images?q=tbn:7agzdcFyZ715EM:http://files.walerian.info/Funny/Animals/funny-pictures-firefox-file-transfer-is-complete.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
        [webView loadData:data MIMEType:@"application/jpg" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://google.com"]];

答案 4 :(得分:3)

我遇到了同样的问题,我在其他地方发现你必须在baseUR L参数中提供一个值。我也有编码集:

textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://localhost/"]];

nil参数中有baseURL时,它将无法加载。通过放置基本上不相关的东西,MS文档都可以工作。

答案 5 :(得分:1)

您可能想尝试将代理人分配给webview并实施该方法:

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

更具体地了解您获得的错误。如果没有被调用,请实现方法:

- (void)webViewDidFinishLoad:(UIWebView *)webView

同样,只是为了确保正在发生,否则UIWebView可能会出现问题(假设您没有从{{1}返回NO })

答案 6 :(得分:0)

扩展Ed Marty的评论:

放入基本64图像的HTML命令是:

<img src="data:image/png;base64,##PUT THE BASE64 DATA HERE###" />

我的网站上有一个类别(我不知道它来自哪里,而不是我......),它将NSData转换为它的Base64字符串表示。

Header Implementation

很容易做到,假设'imageData'是包含图像的NSData变量: [imageData base64Encoding]进入上面的字符串。

答案 7 :(得分:0)

试试这段代码

// 1) Get: Get string from “outline.plist” in the “DrillDownSave”-codesample.
savedUrlString = [item objectForKey: @"itemUrl"];

// 2) Set: The url in string-format, excluding the html-appendix.
NSString *tempUrlString = savedUrlString;

// 3) Set: Format a url-string correctly. The html-file is located locally.
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:tempUrlString ofType:@”html”];

// 4) Set: Set an “NSData”-object of the url-sting.
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];

// 5. Gets the path to the main bundle root folder
NSString *imagePath = [[NSBundle mainBundle] resourcePath];

// 6. Need to be double-slashes to work correctly with UIWebView, so change all “/” to “//”
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];

// 7. Also need to replace all spaces with “%20″
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

//  Load:   Loads the local html-page.
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:/%@//",imagePath]]];

答案 8 :(得分:0)

这是另一种方法:

将下载的图像保存到文档文件夹中。 然后获取该图像的网址。然后写一个简单的html文件 在IMG SRC标记中使用该图像URL。

NSLog(@"url=%@", fileURL); // fileURL is the image url in doc folder of your app


//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/toOpen.html",
                      documentsDirectory];

//create simple html file and format the url into the IMG SRC tag
NSString *content = [NSString stringWithFormat:@"<html><body><img src=%@></body></html>",fileURL];
//save content to the documents directory
[content writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil]; // now we have a HTML file in our doc

// open the HTML file we wrote in the webview

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"life.html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[yourWebView loadRequest:request];

答案 9 :(得分:0)

NSString *pathForFile = [[NSBundle mainBundle] pathForResource: @"fireballscopy" ofType: @"gif"];
    NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];
    [Web_View loadData:dataOfGif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];