Multiple Buttons for one webView from different Controller

Viewed 28

Hello my aim is to use on webView in WebController from buttons which are in different controllers. The problem is that my code works on one Controller but not from other two, even though the code is the same.

webView:

var receivedUrl: URL!
@IBOutlet weak var showPage: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    //let url = URL(string: "https://kbtu.edu.kz/en/kbtu-virtual-tour")
    //let request = URLRequest(url: url!)
    let request = URLRequest(url: receivedUrl)
    showPage.load(request)

firstViewController which works with web view:

 var urlToPass: URL!
@IBAction func passUrl(_ sender: UIButton) {
    urlToPass = URL(string: "https://kbtu.edu.kz/en/kbtu-virtual-tour")
    performSegue(withIdentifier: "thirdSegue", sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    guard let destination = segue.destination as? WebViewController else { return }
    destination.receivedUrl = urlToPass
}

second which doesn't work:

class AlumnuViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

var urlToPass: URL!
@IBAction func showWeb(_ sender: UIButton) {
    
    urlToPass = URL(string: "https://kbtu.edu.kz/en/alumni-kbtu-en")
    performSegue(withIdentifier: "fifthSegue", sender: nil)
    
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    super.prepare(for: segue, sender: sender)
    
    guard let destination = segue.destination as? WebViewController else { return }
    destination.receivedUrl = urlToPass
}
1 Answers

You prepare the segue before you perform it but at that point urlToPass is still nil.

According to Apple Documentation:

The default implementation of this method does nothing. Subclasses override this method and use it to configure the new view controller prior to it being displayed

Moving your configuration logic inside prepare(for segue: UIStoryboardSegue, sender: Any?), rather than @IBAction func showWeb(_ sender: UIButton) should solve the problem.

Related