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

时间:2013-04-24 07:28:22

标签: objective-c xcode cocoa 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加载到图片中?

2 个答案:

答案 0 :(得分:0)

如果它只有一个没有相对链接的html页面,除了图像,您可以设置请求的基本网址

这意味着:所有相对网址都被视为相对于此基本网址


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

你唯一的选择是将html重写为仅使用绝对URL而不是本地的任何东西,然后设置基本网址。

答案 1 :(得分:0)

好的,这是久经考验的代码。应该适合你。

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