2016-11-21 158 views
0

我正在尝试将用户交互从popOver视图传递给ViewController,然后与WKWebView进行交互。将值传递给WKWebView Swift

目前选定的呼叫 ViewController().callViewControllerMethod() 这种方法正常工作时和不调用callViewControllerMethod()的酥料饼有按钮其中。

范围内callViewControllerMethod()是在WKWebView上评估JavaScript的一些代码。当代码运行它打evaluateJavascript代码并引发"fatal error: unexpectedly found nil while unwrapping an Optional value"

但我不知道为什么 - 这是内evaluateJavascript功能工作正常,如果直接从ViewController叫,但前提是直接调用的JavaScript。

任何想法的人?

酥料饼的代码

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

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

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

视图控制器代码

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

请提供一个代码示例,以确切地说明问题发生的位置。 – paulvs

+0

“但我不知道为什么” - 编译器意外地发现零,同时展开一个可选值。这是在没有提供上下文代码的情况下得到的最佳答案:/ – Danoram

+0

对不起,如果我添加一些代码会有帮助;) – kb12abz

回答

0

ViewController().callViewControllerMethod()就是为什么你的错误,你基本上创建ViewController新的实例,并告诉它做什么,这是不一样的作为目前的ViewController实例你有

要解决你的问题,你必须创建一个协议/ del egate PopOver告诉ViewController自己执行callViewControllerMethod

+0

好的,谢谢,这很有道理为什么我得到零 - 你知道我在哪里可以找到如何做代表? - 我是一个新的斯威夫特:/ – kb12abz

+0

有很多教程,你可以检查[this](http://stackoverflow.com/questions/24099230/delegates-in-swift)或[this](http:// useyourloaf.com/blog/quick-guide-to-swift-delegates/) – Tj3n