【问题标题】:OSX Swift webview load local fileOSX Swift webview 加载本地文件
【发布时间】:2015-01-16 06:20:04
【问题描述】:

我知道这已经被问过很多次了,我已经阅读了quiteafewquestions 并在谷歌上搜索了几天,到目前为止没有成功。

我只想在桌面应用程序中加载一个本地 html 文件,事实上对于这个项目我需要一个 JS 库,并且大部分已经作为网页完成(css、js 和 html,不需要服务器端处理) .我不想强迫应用程序从互联网服务器加载网页,以免强迫用户连接互联网。不用说我对 Swift 和苹果开发完全没有经验。

现在这是我遇到的问题: ide 对参数的抱怨,我似乎无法正确处理它们。

这里是我最新代码的 sn-p 供参考:

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: Extra argument in call/path/TestWebView/AppDelegate.swift:32:36: Missing argument for parameter 'cachePolicy' in call

此时try1和try2输出“main.html”,try3和try4输出nil,try5输出“(Function)”

文件夹的结构是这样的:

我添加了文件夹“web”作为参考(正如另一个问题中所建议的那样),但我怀疑这是否可以只运送一个包裹......

我不知道是否有任何区别,但我不是针对 iOS,我希望这是一个桌面应用程序。

任何建议将不胜感激

【问题讨论】:

    标签: macos swift webview local


    【解决方案1】:

    阅读this post in the apple forums 并将其与this other question 放在一起后,我能够提出以下工作代码:

    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 调用的所有相关文件。
    • @EdiBudimilic 在我的情况下,它没有破坏我的任何相对路径。
    猜你喜欢
    • 2013-10-05
    • 2014-07-04
    • 1970-01-01
    • 2022-06-25
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多