MAC应用程序开发WKWebView只是无法加载页面。想不通为什么



我的项目中有一个本地HTML,这是一个非常简单的项目,我只是无法在我的mac应用程序中显示它;不知道为什么。

@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
setWkWebView()
loadHtml()
}
func setWkWebView(){
webView.navigationDelegate = self
let config = webView.configuration
let preference = WKPreferences()
preference.javaEnabled = true
let wkUserController = WKUserContentController()
wkUserController.add(self, name: "jsToSwift")
config.preferences = preference
config.userContentController = wkUserController
}
func loadHtml(){
let path = Bundle.main.path(forResource: "test.html", ofType: nil)
let htmlString:String?
do {
htmlString = try String.init(contentsOfFile: path!, encoding: .utf8)
} catch {
htmlString = nil
}
let urlString = "https://www.bilibili.com"
webView.load(URLRequest(url: URL(string: urlString)!))
// webView.loadHTMLString(htmlString!, baseURL: URL(string: path!))
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message)
if (message.name == "jsToSwift"){
print("jsToSwift success")
let buttonIndicat = NSButton(frame: NSRect(x: 30, y: 30, width: 70, height: 70))
buttonIndicat.title = "jsToSwift"
webView.addSubview(buttonIndicat)
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error)
}

一种可能是因为MacOS应用程序(在最新的OS/Xcode版本中(默认情况下是沙盒。您可能需要选择"传出连接(客户端(",以便发出WWW和(WWW工作所必需的(DNS请求。本地文件访问也有限制。

单击下面的"功能"下的Xcode权利部分的图片。

xcode授权

最新更新