Cocoa WebView - 加载本地HTML页面 [英] Cocoa WebView - Loading a local HTML page

查看:505
本文介绍了Cocoa WebView - 加载本地HTML页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览了不少,我还是无法想象出来。我已经添加了一个HTML页面及其图像目录到我的项目Xcode中的资源组(复制它们)。

After browsing quite a bit, I still can't figure this out. I've added a HTML page and its images directory into my project Resources group in Xcode (Copied them over).

当我尝试加载WebView以下代码

When I try to load the WebView with the following code, the text is displayed fine, but the images aren't loaded.

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"index.html"];
NSString *htmlContent = [NSString stringWithContentsOfFile:path];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[[tempWebView mainFrame] loadHTMLString:htmlContent baseURL:url];

编辑:抱歉的延迟,这里有一些基本的html失败。

Sorry about the delay, here's some basic html that failed.

<html>
    <body> 
        <img src="images/bg.png"></img> 
    </body>
</html>

我编辑的代码如下 -

And my edited code looks like this -

NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:path];
[[webView1 mainFrame] loadRequest:[NSURLRequest requestWithURL:url]];

EDIT2:刚刚意识到这是路径的问题。显然< img src =images / bg.png> 不工作,但如果我将bg.png复制到根目录,并说< img src =bg.png> 一切正常。

Just realized it was an issue with the path. Apparently <img src = "images/bg.png"> doesn't work, but if I copy bg.png to the root directory and say <img src = "bg.png"> everything works fine. I'm still not sure where I'm going wrong with this.

推荐答案

请考虑执行以下操作:


  1. 要求套件提供正确的路径

  2. 要求套件提供正确的网址。 (需要Mac OS X 10.6或更高版本。)

  3. 不会直接将HTML内容注入框架,要求WebView加载网址

  1. Instead of getting the resource path and stapling a subpath onto it yourself, ask the bundle to give you the correct path.
  2. Instead of handling a path at all, ask the bundle to give you the correct URL. (Requires Mac OS X 10.6 or later.)
  3. Instead of injecting HTML contents directly into the frame, ask the WebView to load the URL.

这会将您的代码缩减为两行,如果HTML代码正确,则会正常工作。

This reduces your code to two lines that, if the HTML code is correct, will work.

这篇关于Cocoa WebView - 加载本地HTML页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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