简体   繁体   English

将值传递给WKWebView Swift

[英]Passing Values to WKWebView Swift

I am attempting to pass a users interaction from a popOver view to ViewController to then interact with WKWebView. 我试图将用户交互从popOver视图传递到ViewController,然后与WKWebView交互。

Currently the popOver has Buttons which when selected calls ViewController().callViewControllerMethod() this method works correctly and does call callViewControllerMethod() . 当前popOver具有Buttons,当选择该按钮时,它将调用ViewController().callViewControllerMethod()此方法可以正常工作,并且确实调用callViewControllerMethod()

Within callViewControllerMethod() is some code to evaluateJavascript on a WKWebView. callViewControllerMethod()有一些代码可以在WKWebView上评估Javascript。 When the code is ran it hits the evaluateJavascript code and throws "fatal error: unexpectedly found nil while unwrapping an Optional value" 运行该代码时,它会触碰evaluateJavascript代码并抛出"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. 但我不知道为什么-这是内部的JavaScript evaluateJavascript功能工作正常,如果直接从所谓ViewController ,但前提是直接调用。

Any ideas anyone? 有任何想法吗?

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

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 这个ViewController().callViewControllerMethod()是导致错误的原因,您基本上是在创建ViewController新实例并告诉它执行某些操作,这与您拥有的当前ViewController实例不同

To fix your problem, you have to create a protocol/delegate on the PopOver to tell the ViewController to execute callViewControllerMethod from itself 要解决您的问题,您必须在PopOver上创建一个协议/委托以告诉ViewController从自身执行callViewControllerMethod

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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