简体   繁体   English

使用Swift 3在MacOS应用程序中加载WebView中的本地HTML文件

[英]Load local HTML file in WebView with Swift 3 in a macOS app

I'm having a hard time with this one. 我很难用这个。 I'm not really sure what I'm doing wrong. 我不确定我做错了什么。

Here's how I'm doing it for iOS UIWebView: 以下是我为iOS UIWebView做的事情:

    let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let request = NSURLRequest(url: url!)
    webView.loadRequest(request as URLRequest)

Unfortunately, that doesn't work for an OS X app. 不幸的是,这对OS X应用程序不起作用。 I found some code which used to work with Swift 2. I made some changes to it to make it work with Swift 3, but I'm still getting an error. 我发现了一些曾经与Swift 2一起使用的代码。我对它进行了一些更改以使其与Swift 3一起使用,但我仍然遇到错误。

    let url = Bundle.main.url(forResource: "index", withExtension: "html")
    self.webView.mainFrame.load(NSURLRequest(URL: NSURL(string: url)!))

What are my options? 我有什么选择? Thanks in advance! 提前致谢!

Try this simple steps, for me works 尝试这个简单的步骤,对我而言

let urlpath = Bundle.main.path(forResource: "index", ofType: "html");
let requesturl = URL(string: urlpath!)
let request = URLRequest(url: requesturl!)
webView.mainFrame.load(request)

I have fixed my issue using sdbrain's answer on another thread. 我已经在另一个线程上使用sdbrain的答案修复了我的问题。

Basically remove your root folder from your project and opt it to another folder. 基本上从项目中删除根文件夹并将其选择到另一个文件夹。 Then, drag the root folder from finder to Xcode directly. 然后,将根文件夹从finder直接拖到Xcode。 You will see options of creating groups for added folders or creating folder references. 您将看到为添加的文件夹创建组或创建文件夹引用的选项。 And a checkbox displaying copy if needed. 并根据需要显示复制的复选框。 I have selected, copy if needed options and creating folder references options. 我已经选择,复制需要的选项和创建文件夹引用选项。

My below code worked 我的下面的代码工作

    if let path = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "wwwroot") {
        webView.loadRequest(URLRequest(url: URL(fileURLWithPath: path)) )
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM