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

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

问题描述

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

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

如果我引用没有相对路径的图像并将引用的图像放在根路径中,这样可以正常工作在目标 - >复制XCode中的捆绑资源,但是我无法使用我的html文件中显示的相对路径。必须有一种方法可以做到这一点,我有很多图像,CSS,javascript文件,我想加载到webview中,我希望不必拥有根目录中的所有内容,并且必须更改我的网络中的所有引用app。

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:@indexofType:@ htmlinDirectory:@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.

Swift 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天全站免登陆