我有一个非常简单的iOS应用程序,带有uiwebview加载一个非常简单的测试页面(test.html):
<html>
<body>
<img src="img/myimage.png" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我将此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];
Run Code Online (Sandbox Code Playgroud)
如果我在没有相对路径的情况下引用图像并将引用的图像放在根目录下的根目录下 - >在XCode中复制捆绑资源,这可以正常工作,但是我无法使用我的html文件中显示的相对路径.必须有一种方法可以做到这一点,我有很多图像,CSS,javascript文件,我想加载到webview中,我希望不必拥有根目录中的所有内容,并且必须更改我的网站中的所有引用应用程序.
小智 285
这是如何加载/使用具有相对引用的本地html.
使用下面给出的代码.它应该像魅力一样工作.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
[webview loadRequest:[NSURLRequest requestWithURL:url]];
现在,html中的所有相关链接(如img/.gif,js / .js)都应该得到解决.
斯威夫特3
if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}
Run Code Online (Sandbox Code Playgroud)
Wel*_*les 24
在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)
}
Run Code Online (Sandbox Code Playgroud)
我把所有东西塞进了一条线(我知道不好)并且没有任何麻烦:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test"
ofType:@"html"]
isDirectory:NO]]];
Run Code Online (Sandbox Code Playgroud)
我只是这样做:
UIWebView *webView = [[[UIWebView alloc] init] autorelease];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
Run Code Online (Sandbox Code Playgroud)
其中"index.html"相对引用图像,CSS,javascript等.
| 归档时间: |
|
| 查看次数: |
114784 次 |
| 最近记录: |