UIWebView加载服务器HTML,如何加载本地图像?

问题描述:

下面是加载HTML代码UIWebView加载服务器HTML,如何加载本地图像?

UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
[[NSBundle mainBundle] pathForResource:@"111" ofType:@"jpg"]; 
NSURLRequest *repuest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.5/index.html"]]; 
[webView loadRequest:repuest]; 
[self.view addSubview:webView]; 

下面是HTML代码

<img src="111.jpg" /> 
<hr /> 

这样做的图像无法加载。在这种情况下,如何将HTML加载到图片中?

+1

可能的重复http://*.com/questions/747407/using-html-and-local-images-within-uiwebview。 – 2013-04-24 07:30:49

+0

也许你需要指定一个'baseurl'? – 2013-04-24 07:31:11

+0

不重复。我的HTML位于服务器之上。 – 2013-04-24 07:36:47

如果在没有相对链接到任何东西,但图像的只有一个HTML页面,您可以设置基本URL请求

,这意味着:所有相对URL被认为是相对于这个基本URL


但是如果你的html在服务器和本地图像上使用css/js/html文件,你将需要2个基址,这是不可能的。

你唯一的选择就是重写html,只对绝对URL使用绝对URL,然后设置基本URL。

+0

(绝对网址不酷但我没有看到另一个非hackisch的方式 – 2013-04-24 07:52:12

+0

仅供参考:您也可以动态地重写html,下载它,搜索所有img标签并替换它) – 2013-04-24 07:53:52

+0

Consid可持续的复杂性啊。 – 2013-04-24 07:56:56

好的,这是经过验证和测试的代码。应该为你工作。

NSString *imagePath; 
NSBundle *bundle = [NSBundle mainBundle]; 
NSString *path = [bundle bundlePath]; 
imagePath = [NSBundle pathForResource:@"111" ofType:@"jpg" inDirectory:path]; 

NSString *fixedURL = [imagePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
fixedURL = [NSString stringWithFormat:@"file://%@",fixedURL]; 
NSString *commentHtml = [NSString stringWithFormat:@"<img src=\"%@\"/>", fixedURL]; 
NSString *html3 = [NSString stringWithFormat:@"<html><head/><body><div><b>COMMENTS:</b></div>%@</body></html>", commentHtml]; 

[webView loadHTMLString:html3 baseURL:nil]; 
+0

我需要在上面的HTML中加载本地图像。 – 2013-04-24 08:05:39

+0

你有哪些地方形象?在我们的文档目录中? – 2013-04-24 08:07:18

+0

APP中的图片,以上服务器上的HTML。 – 2013-04-24 08:27:22