【发布时间】:2018-10-12 05:38:51
【问题描述】:
我希望能够加载位于我的应用程序包之外的 HTML 文件,目前我可以通过执行以下操作来加载该文件: 此应用适用于 MacOS
let htmlPath = Bundle.main.path(forResource: "/html/index", ofType:"html")
let url = URL(fileURLWithPath: htmlPath!)
let request = URLRequest(url: url)
webView.load(request)
这是从我的项目资源中加载名为 index 的 HTML 文件。我希望它从用户定义的位置读取文件。这样用户就可以告诉应用 HTML 文件在他们的桌面上
我的猜测是代码将类似于以下内容:
@IBOutlet var fileLocation: NSTextField
@IBOutlet var webView: WKWebView!
var file = fileLocation.StringValue
let htmlPath = Bundle.main.path(forResource: "\(file)", ofType:"html")
let url = URL(fileURLWithPath: htmlPath!)
let request = URLRequest(url: url)
webView.load(request)
但是,上面的代码会导致崩溃并出现错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
错误是否与路径在 Bundle.main.path 中有关?
如果是这样,我也会改变什么?
【问题讨论】:
标签: html swift xcode macos webview