-1

I'm using a WKWebView to open URLs from a list contained within a TableView. However, I cannot figure out how to pass URLs from the TableView controller to the WKWebView class I've created. My class inherits from UIViewController.

So far I've attempted to create a custom initializer, following Aaron Rasmussen's instructions for How to write init methods of a UIViewController in Swift, but when I do so I end up with the error:

Incorrect argument label in call (have 'url:', expected 'coder:')

and I can't figure out how to call the new initializer instead of the default one (the super's init?).

Any advice would be extremely appreciated. I'm not sure if I'm close to an optimal solution, or if I'm missing something that would making passing the URL to the WKWebView easy.

WKWebView class:

class WKBrowserController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!
    var webURL: URL

    init(url: URL, nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?){
        self.webURL = url
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        self.webURL = URL(string: "www.google.com")!
        super.init(coder: aDecoder)
    }

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        self.view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.load(URLRequest(url: webURL))
    }

TableView Controller

class TableViewController: UITableViewController {

    ...

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        showHome(indexPath: indexPath)
    }

    func showHome(indexPath: IndexPath){

        if let url = URL(string: urlString){
            let customWebController = WKBrowserController(url: urlString) // Error here
            present(customWebController, animated: true)
        }
    }
gsamerica
  • 153
  • 1
  • 3
  • 18

1 Answers1

1

Why not just

class WKBrowserController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView?
    var webURL: URL? { didSet {
            self.navigate()
        }
   }

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        self.view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigate()
    }

    fileprivate func navigate() {
        if let url = self.webURL {
                webView.load(URLRequest(url: url))
        }
    }

And then in the table view

func showHome(indexPath: IndexPath){

        if let url = URL(string: urlString) {
            let customWebController = WantedBrowserController()
            customWebController.webURL = url
            present(customWebController, animated: true)
        }
    }
zaitsman
  • 8,984
  • 6
  • 47
  • 79