0

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")
            }
        }
    }
}
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
kb12abz
  • 1
  • 3
  • Please provide a code sample demonstrating exactly where the problem occurs. – paulvs Nov 21 '16 at 23:00
  • "But I have no idea why" - the compiler unexpectedly found nil while unwrapping an Optional value. This is the best answer you will get without providing any code from the context :/ – Danoram Nov 21 '16 at 23:00
  • sorry does help if i add some code ;) – kb12abz Nov 21 '16 at 23:08

1 Answers1

0

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

Tj3n
  • 9,837
  • 2
  • 24
  • 35
  • okay thanks that makes sense why I'm getting nil - do you know where i can look for how to do delegate? - Im a new to Swift :/ – kb12abz Nov 22 '16 at 13:35
  • There are many tutorial for that, you can check [this](http://stackoverflow.com/questions/24099230/delegates-in-swift) or [this](http://useyourloaf.com/blog/quick-guide-to-swift-delegates/) – Tj3n Nov 23 '16 at 03:20