在 uiwebview 中使用本地 html 从相对路径加载资源 [英] Load resources from relative path using local html in uiwebview

查看:10
本文介绍了在 uiwebview 中使用本地 html 从相对路径加载资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 iOS 应用程序,带有一个加载一个非常简单的测试页面 (test.html) 的 uiwebview:

I have a very simple iOS app with a uiwebview loading a very simple test page (test.html):

<html>
<body>
<img src="img/myimage.png" />
</body>
</html>

我将此 test.html 文件加载到我的网络视图中:

I load this test.html file into my web view:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:html baseURL:baseUrl];

如果我在没有相对路径的情况下引用图像并将引用的图像放在根路径下 Targets -> Copy Bundle Resources 在 XCode 下,这可以正常工作,但是我无法使用相对路径,如图所示我的 html 文件.必须有办法做到这一点,我有很多图像、css、javascript 文件要加载到 web 视图中,我不想将所有内容都放在根目录中,并且必须更改我的 web 中的所有引用应用程序.

This works fine if I reference the image without the relative path and put the referenced image in the root path under Targets -> Copy Bundle Resources within XCode, however I can't get it to work with the relative path as shown in my html file. There must be a way to do this, I have lots of images, css, javascript files that I want to load into the webview and I would like not to have to have everything in the root and have to change all the references in my web app.

推荐答案

这是如何加载/使用具有相对引用的本地 html.

This is how to load/use a local html with relative references.

  1. 将资源拖到您的 xcode 项目中(我从 finder 窗口中拖了一个名为 www 的文件夹),您将获得两个选项为任何添加的文件夹创建组"和为任何添加的文件夹创建文件夹引用".
  2. 选择创建文件夹引用.."选项.
  3. 使用下面给出的代码.它应该像魅力一样发挥作用.

  1. Drag the resource into your xcode project (I dragged a folder named www from my finder window), you will get two options "create groups for any added folders" and "create folders references for any added folders".
  2. Select the "create folder references.." option.
  3. Use the below given code. It should work like a charm.

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
[webview loadRequest:[NSURLRequest requestWithURL:url]];

现在您在 html 中的所有相关链接(如 img/.gif、js/.js)都应该得到解析.

Now all your relative links(like img/.gif, js/.js) in the html should get resolved.

斯威夫特 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }

这篇关于在 uiwebview 中使用本地 html 从相对路径加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆