OSX Swift中加载本地文件的webview

5

我知道这个问题已经被问了很多次,而且我已经读过很多相关内容,并且已经搜索了几天,但目前还没有成功。

我只想在一个桌面应用程序中加载一个本地html文件,实际上,为了这个项目,我需要一个JS库,大部分内容已经作为一个网页(CSS、JS和HTML,不需要服务器端处理)完成。我不想强制应用程序从互联网服务器加载网页,这样不会强迫用户拥有互联网连接。不用说,我对Swift和苹果开发完全没有经验。

现在我的问题是:

enter image description here

IDE对参数进行投诉,我似乎无法正确获取它们。

以下是我的最新代码片段:

class AppDelegate: NSObject, NSApplicationDelegate
{
    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var webView: WebView!
    typealias NSSize = CGSize

    func applicationDidFinishLaunching(aNotification: NSNotification?)
    {
        self.window.title = "Chess Study Room"

        var try1 = "main.html";
        println(try1);

        var try2 = NSURL(string: try1)!;
        println(try2);

        var try3 =
        NSBundle.URLForResource("main", withExtension: "html", subdirectory: "web", inBundleWithURL: try2);
        println(try3);

        var try4 = NSBundle.pathForResource("main", ofType: "html", inDirectory: "web");
        println(try4);

        var try5 = NSString.stringByAppendingPathComponent("main.html");
        println(try5);
        // var myInternalUrl = NSURL(string: myInternalHtml)!;
        //NSLog("%s", myInternalHtml!);
        var request = NSURLRequest(try1,
            NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
            60
        );

        self.webView.frameLoadDelegate = self;
        self.webView.mainFrame.loadRequest(
            request!
        );
    }

但是从我的gif可以看出,我也尝试了其他方法。完整的错误信息是/path/TestWebView/AppDelegate.swift:32:35: 调用中有额外的参数/path/TestWebView/AppDelegate.swift:32:36: 调用中缺少参数 'cachePolicy'
此时,try1和try2输出"main.html",try3和try4输出nil,try5输出"(Function)"。
文件夹的结构如下: enter image description here 我将文件夹"web"作为引用添加了进来(在另一个问题中得到的建议),但我怀疑这种方法是否适用于只发布一个软件包...
我不知道是否有任何区别,但我不是针对iOS,我希望这是一个桌面应用程序。
非常感谢您的建议。
1个回答

3

阅读苹果论坛上的这个帖子并结合这个问题,我成功编写了以下代码:

func applicationDidFinishLaunching(aNotification: NSNotification?)
    {
        self.window.title = "My App Title"

        var try6 = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("main", ofType:"html")!)

        var request = NSURLRequest(URL: try6!);

        self.webView.frameLoadDelegate = self;
        self.webView.mainFrame.loadRequest(request);
    }

路径不是相对的。它可以工作,但会破坏 HTML 调用的所有相对文件。 - Edi Budimilic
@EdiBudimilic 在我的情况下并没有出现问题,它没有破坏任何相对路径。 - Purefan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接