扩展类中的字段为null

时间:2019-03-06 19:43:46

标签: swift wkwebview

我创建了一个WKWebView来使用我的App,我需要Swift与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 })
        }
    }
}

此错误: enter image description here

我在didReceive函数中添加了下一个代码:

extension FirstViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "jsHandler" {
            if self.wk == nil {
                print("WK is Null!")
            }
        }
    }
}

并且: enter image description here

不能在扩展类中引用对象?

1 个答案:

答案 0 :(得分:3)

您永远不会在path = "C:\Report\" fileSaveName = Application.GetSaveAsFilename(InitialFileName:=path & "Report", _ fileFilter:="Excel Workbooks (*.xls; *.xlsx),*.xls;*.xslx") If fileSaveName <> False Then Application.DisplayAlerts = True ActiveWorkbook.SaveAs Filename:=fileSaveName, FileFormat:=xlOpenXMLWorkbook End If 中将网络视图分配给wk

viewDidLoad

或者只是:

override func viewDidLoad() {
    ...

    let wk = WKWebView(frame: .zero, configuration: config)
    // assign the local variable to instance property
    self.wk = wk
    view.addSubview(wk)
}