我创建了一个WKWebView来使用我的应用程序,我需要和Javascript进行快速对话,除了这个之外,一切都正常!
import UIKit
import WebKit
class FirstViewController: UIViewController {
var wk: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
let user = WKUserContentController()
user.add(self, name: "jsHandler")
config.userContentController = user
let wk = WKWebView(frame: .zero, configuration: config)
view.addSubview(wk)
}
}
extension FirstViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler" {
// HERE HAPPENS THE ERROR
self.wk.evaluateJavaScript("chamaLista( '\(value!)' );", completionHandler: { (Any, Error) in })
}
}
}
此错误:
我在didReceive函数中添加下一个代码:
extension FirstViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler" {
if self.wk == nil {
print("WK is Null!")
}
}
}
}
以及:
不能引用扩展类中的对象???
最佳答案
在您的wk
中,您从未将webview分配给viewDidLoad
:
override func viewDidLoad() {
...
let wk = WKWebView(frame: .zero, configuration: config)
// assign the local variable to instance property
self.wk = wk
view.addSubview(wk)
}
或者只是:
override func viewDidLoad() {
...
// assign directly to instance property, don't use local variable
wk = WKWebView(frame: .zero, configuration: config)
view.addSubview(wk)
}
关于swift - 扩展类中的字段为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55031052/