簡體   English   中英

將值傳遞給WKWebView Swift

[英]Passing Values to WKWebView Swift

我試圖將用戶交互從popOver視圖傳遞到ViewController,然后與WKWebView交互。

當前popOver具有Buttons,當選擇該按鈕時,它將調用ViewController().callViewControllerMethod()此方法可以正常工作,並且確實調用callViewControllerMethod()

callViewControllerMethod()有一些代碼可以在WKWebView上評估Javascript。 運行該代碼時,它會觸碰evaluateJavascript代碼並拋出"fatal error: unexpectedly found nil while unwrapping an Optional value"

但我不知道為什么-這是內部的JavaScript evaluateJavascript功能工作正常,如果直接從所謂ViewController ,但前提是直接調用。

有任何想法嗎?

PopOver代碼

class BackgroundViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func button1(_ sender: AnyObject!) {
        print("button 1 selected")
        ViewController().callViewControllerMethod()
    }
}

ViewController代碼

class ViewController: UIViewController, WKNavigationDelegate, UISearchBarDelegate {
    func callViewControllerMethod() {
        print("got to the method")
        webView.evaluateJavaScript("document.body.style.background = \"white\";") { (result, error) in
            if error != nil {
                print(result as Any)
            }
            else {
                print("background code completed")
            }
        }
    }
}

這個ViewController().callViewControllerMethod()是導致錯誤的原因,您基本上是在創建ViewController新實例並告訴它執行某些操作,這與您擁有的當前ViewController實例不同

要解決您的問題,您必須在PopOver上創建一個協議/委托以告訴ViewController從自身執行callViewControllerMethod

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM