【问题标题】:Load local HTML file in WebView with Swift 3 in a macOS app在 macOS 应用程序中使用 Swift 3 在 WebView 中加载本地 HTML 文件
【发布时间】:2016-12-29 10:41:47
【问题描述】:

我很难处理这个。我不确定我做错了什么。

这是我为 iOS UIWebView 做的事情:

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

很遗憾,这不适用于 OS X 应用程序。我找到了一些曾经与 Swift 2 一起使用的代码。我对其进行了一些更改以使其与 Swift 3 一起使用,但我仍然遇到错误。

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

我有哪些选择?提前致谢!

【问题讨论】:

    标签: html swift xcode macos webview


    【解决方案1】:

    试试这个简单的步骤,对我有用

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

    【讨论】:

    • 但是您将资源放在哪里?我的意思是什么目录?
    • 作为一个简单的资源,拖放到你的Xcode项目中
    【解决方案2】:

    我已在另一个线程上使用sdbrain's 回答解决了我的问题。

    基本上从您的项目中删除您的根文件夹并将其选择到另一个文件夹。然后,直接将根文件夹从 finder 拖到 Xcode 中。 您将看到为添加的文件夹创建组或创建文件夹引用的选项。如果需要,还有一个显示副本的复选框。我已经选择,如果需要,复制选项和创建文件夹引用选项。

    我下面的代码工作了

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

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 2014-02-28
      • 1970-01-01
      相关资源
      最近更新 更多