在UIWebView中使用HTML和本地图像

Jas*_*ien 162 html iphone uiwebview uikit ios

我的应用程序中有一个UIWebView,我想用它来显示一个链接到另一个URL的图像.

我正在使用

<img src="image.jpg" /> to load the image.
Run Code Online (Sandbox Code Playgroud)

问题是图像没有加载(即无法找到),即使它已作为资源添加到我的项目中并被复制到包中.

我已经尝试使用NSBundle来获取图像的完整路径并使用它,它仍然没有显示在Web视图中.

有任何想法吗?

Ada*_*der 290

使用相对路径或文件:路径来引用图像不适用于UIWebView.相反,您必须使用正确的baseURL将HTML加载到视图中:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样引用您的图像:

<img src="myimage.png">
Run Code Online (Sandbox Code Playgroud)

(来自uiwebview再次访问)

  • [[NSBundle mainBundle] bundleURL]我们可以将它用作bundleURL (15认同)
  • 所有这一切对我来说都是在我的webview中给我一个字符串,我为我的htmlString定义.即它在页面上显示的只是"tour.html" (2认同)

Lit*_*T.V 46

用这个:

[webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];
Run Code Online (Sandbox Code Playgroud)

  • 这是一个方便的单行版本的接受答案 - 没有伤害做到这里. (13认同)
  • @Jasarien亚当亚历山大回答是唯一的解决方案,直到2009年8月.但是从Max OS X版本10.6开始,这个新属性"bundleURL"被添加到NSBundle中.无需使用bundlePath并转换为URL.因此,对于工作在高于10.6的版本的人来说,这提供了更好的解决方案. (9认同)
  • 但你的答案与3年前发布的答案相同......你的答案没有什么不同,它不需要发布,因为已接受的答案已涵盖你发布的内容. (5认同)

Ant*_*ton 24

我也遇到了这个问题.在我的情况下,我正在处理一些未本地化的图像和其他用于多种语言的图像.基本URL没有为我获取本地化文件夹中的图像.我通过以下方式解决了这个问题:

// make sure you have the image name and extension (for demo purposes, I'm using "myImage" and "png" for the file "myImage.png", which may or may not be localized)
NSString *imageFileName = @"myImage";
NSString *imageFileExtension = @"png";

// load the path of the image in the main bundle (this gets the full local path to the image you need, including if it is localized and if you have a @2x version)
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageFileName ofType:imageFileExtension];

// generate the html tag for the image (don't forget to use file:// for local paths)
NSString *imgHTMLTag = [NSString stringWithFormat:@"<img src=\"file://%@\" />", imagePath];
Run Code Online (Sandbox Code Playgroud)

然后,在加载内容时,在UIWebView HTML代码中使用imgHTMLTag.

我希望这可以帮助遇到同样问题的人.


小智 7

尝试使用base64图片字符串。

NSData* data = UIImageJPEGRepresentation(image, 1.0f);

NSString *strEncoded = [data base64Encoding];   

<img src='data:image/png;base64,%@ '/>,strEncoded
Run Code Online (Sandbox Code Playgroud)


小智 6

我有一个类似的问题,但所有的建议都无济于事.

但问题是*.png本身.它没有alpha通道.不知何故,Xcode在部署过程中忽略了没有alpha通道的所有png文件.


MrA*_*An3 5

在斯威夫特 3 中:

webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)
Run Code Online (Sandbox Code Playgroud)

即使图像位于文件夹内且没有任何修改,这对我也有效。