在uiwebview中使用本地html从相对路径加载资源
我有一个非常简单的iOS应用程序,加载了一个非常简单的测试页面(test.html):uiwebview:
<html>
<body>
<img src="img/myimage.png" />
</body>
</html>
我将这个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];
这工作正常,如果我引用没有相对路径的图像,并将引用的图像放在根目录下XCode中的目标 - >复制束资源下,但我不能让它与我的HTML文件中显示的相对路径一起工作。 必须有一种方法可以做到这一点,我有很多图像,CSS,JavaScript文件,我想加载到Web视图中,我不想在根目录中必须包含所有内容,并且必须更改网站中的所有引用应用程序。
这是如何加载/使用具有相关引用的本地html。
使用下面给出的代码。 它应该像魅力一样工作。
 NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];  
 [webview loadRequest:[NSURLRequest requestWithURL:url]];
现在,所有相关链接(如img / .gif,js / .js)都应该被解析。
斯威夫特3
    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }
在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)
}
我把所有东西塞进一条线(坏的我知道)并且没有任何麻烦:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                         ofType:@"html"]
                                                             isDirectory:NO]]];         
上一篇: Load resources from relative path using local html in uiwebview
