Search code examples
segueswift4xcode9

Swift4 Xcode9 Passing variable between ViewControllers through segue


class InstanceViewController: NSViewController{
    @IBOutlet weak var InstanceAddr:NSTextField!
    var input: String = ""
    override func viewDidLoad(){
        super.viewDidLoad()
    }

    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
        InstanceViewController().input = "https://google.com"
        if (segue.identifier?.rawValue == "moveToLoginWindow"){
            let destinationVC = segue.destinationController as! loginWebViewController
            destinationVC.address = input
        }
    }
}

class loginWebViewController: NSViewController{
    @IBOutlet weak var instanceview: WKWebView!
    var address: String?
    override func viewDidLoad(){
        var instanceaddress: String? = address
        super.viewDidLoad()
        var url = URL(string: instanceaddress!)
        var request = URLRequest(url: url!)
        instanceview.load(request)
    }
}

I'm trying to pass variable input: String from InstanceViewController to address: String? in loginWebViewController and load webview with this address. I succeeded loading webview but I can't seem to pass variable through segue moveToLoginWindow. I did everything I could possibly think but nothing worked. Can anyone tell me what I'm doing wrong?


Solution

  • To create a new instance of InstanceViewController inside another instance of the same type makes no sense and causes the issue.

    You have to use input of the current instance:

    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
        input = "https://google.com"
        if segue.identifier?.rawValue == "moveToLoginWindow" {
            let destinationVC = segue.destinationController as! loginWebViewController
            destinationVC.address = input
        }
    }
    

    And as the passed type is non-optional declare address also as non-optional

    var address = ""