简体   繁体   中英

Passing Values to WKWebView Swift

I am attempting to pass a users interaction from a popOver view to ViewController to then interact with WKWebView.

Currently the popOver has Buttons which when selected calls ViewController().callViewControllerMethod() this method works correctly and does call callViewControllerMethod() .

Within callViewControllerMethod() is some code to evaluateJavascript on a WKWebView. When the code is ran it hits the evaluateJavascript code and throws "fatal error: unexpectedly found nil while unwrapping an Optional value"

But I have no idea why - the javascript that is within the evaluateJavascript function works correctly if called directly from ViewController , but only if called directly.

Any ideas anyone?

PopOver Code

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 Code

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")
            }
        }
    }
}

This ViewController().callViewControllerMethod() is why you get the error, you are basically create new instance of ViewController and tell it to do something, it's not the same as the current ViewController instance you have

To fix your problem, you have to create a protocol/delegate on the PopOver to tell the ViewController to execute callViewControllerMethod from itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM