ios 在uiwebview中使用本地html从相对路径加载资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6420925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:26:53  来源:igfitidea点击:

Load resources from relative path using local html in uiwebview

iosuiwebview

提问by Matt Palmerlee

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

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

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

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

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

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

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.

如果我在没有相对路径的情况下引用图像并将引用的图像放在根路径下的目标 -> XCode 中的复制捆绑资源中,则这可以正常工作,但是我无法使用相对路径,如我的 html 文件中所示. 必须有办法做到这一点,我有很多图像、css、javascript 文件,我想加载到 webview 中,我不想把所有东西都放在根目录中,而不必更改我的 web 中的所有引用应用程序。

回答by sdbrain

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

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

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

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

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

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

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

Swift 3

斯威夫特 3

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

回答by Weles

In Swift:

在斯威夫特:

 func pathForResource(  name: String?, 
                        ofType ext: String?, 
                        inDirectory subpath: String?) -> String?  {

  // **name:** Name of Hmtl
  // **ofType ext:** extension for type of file. In this case "html"
  // **inDirectory subpath:** the folder where are the file. 
  //    In this case the file is in root folder

    let path = NSBundle.mainBundle().pathForResource(             "dados",
                                                     ofType:      "html", 
                                                     inDirectory: "root")
    var requestURL = NSURL(string:path!)
    var request = NSURLRequest(URL:requestURL)

    webView.loadRequest(request)
}

回答by PengOne

I crammed everything into one line (bad I know) and had no troubles with it:

我把所有东西都塞进了一行(我知道不好)并且没有遇到任何问题:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                         ofType:@"html"]
                                                             isDirectory:NO]]];         

回答by Old McStopher

I simply do this:

我只是这样做:

    UIWebView *webView = [[[UIWebView alloc] init] autorelease];

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

Where "index.html" relatively references images, CSS, javascript, etc.

其中“index.html”相对引用图像、CSS、javascript 等。

回答by ThisIsNotMe

Swift answer 2.

快速回答2。

The UIWebView Class Referenceadvises against using webView.loadRequest(request):

所述的UIWebView类参考建议不要使用webView.loadRequest(请求):

Don't use this method to load local HTML files; instead, use loadHTMLString:baseURL:.

不要使用此方法加载本地 HTML 文件;相反,使用 loadHTMLString:baseURL:。

In this solution, the html is read into a string. The html's url is used to work out the path, and passes that as a base url.

在这个解决方案中,html 被读入一个字符串。html 的 url 用于计算路径,并将其作为基本 url 传递。

let url = bundle.URLForResource("index", withExtension: "html", subdirectory: "htmlFileFolder")
let html = try String(contentsOfURL: url)
let base = url.URLByDeletingLastPathComponent
webView.loadHTMLString(html, baseURL: base)

回答by skornos

@sdbrain's answer in Swift 3:

@sdbrain 在 Swift 3 中的回答:

    let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
    webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)

回答by Matt Palmerlee

I've gone back and tested and re-tested this, it appears that the only way I can get it to work (since I have some files in the img folder and some in js/css, etc...) is not to use a relative path to my image in the html and have everything referenced to the bundle folder. What a shame :(.

我已经回去测试并重新测试了这个,似乎我可以让它工作的唯一方法(因为我在 img 文件夹中有一些文件,有些在 js/css 等中......)不是在 html 中使用我的图像的相对路径,并将所有内容都引用到捆绑文件夹中。多可惜 :(。

<img src="myimage.png" />

回答by Bently Bobo

In Swift 3.01 using WKWebView:

在 Swift 3.01 中使用 WKWebView:

let localURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "CWP")!)
myWebView.load(NSURLRequest.init(url: localURL) as URLRequest)

This adjusts for some of the finer syntax changes in 3.01 and keeps the directory structure in place so you can embed related HTML files.

这会针对 3.01 中的一些更精细的语法更改进行调整,并保持目录结构就位,以便您可以嵌入相关的 HTML 文件。