Swift 3 WKWebView在不同的View Controller的WKWebView中打开链接(url)

时间:2016-11-16 16:45:37

标签: swift3 wkwebview

I have ViewController1 with WKWebView need open a link inside ViewController2 WKWebView.

我已尝试下面的代码,但不知道如何将request.url传递给第二个ViewController的WKWebView。

 func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    switch navigationType{
                case .linkClicked:
   self.performSegue(withIdentifier: "mySeque", sender:self)


                return false


            default:
                return true

            }
}

1 个答案:

答案 0 :(得分:0)

您需要将FirstWKWebViewController中的URLRequest和WKWebViewConfiguretion传递给SecondWKWebViewController

参考以下实施

在FirstWKWebViewController中将全局变量保持为

var firstURLRequest: URLRequest?

说你的WKWebView是

firstWebView

将代码修改为

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

switch navigationType{

            case .linkClicked:

                 firstURLRequest = request //<---code add
                 self.performSegue(withIdentifier: "mySeque", sender:self)
                 return false

            default:
                return true
        }

}

在SecondWKWebViewController中创建两个变量

var secondURLRequest: URLRequest?
var secondWebConfiguration: WKWebViewConfiguration? 
然后在FirstWKWebViewController中传递WebConfiguration和URLReqest之前的segue调用

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let segueIdentifier = segue.identifier {

        switch segueIdentifier { 
        case "mySeque":

            if let secondWKWebVC = segue.destination as? SecondWKWebViewController {
                if nsurlreq != nil { secondWKWebVC.secondURLRequest = nsurlreq! as URLRequest }
                secondWKWebVC.secondWebConfiguration = firstWebView.configuration     
            } 
        default:
            return
        }
    }

}

然后在SecondWKWebViewController

guard let secondURLRequest = secondURLRequest else 
{ fatalError("No secondURLRequest") }

guard let secondWebConfiguration = secondWebConfiguration else 
{ fatalError("No webConfiguration") }

//WKWebView
seconWKWebView = WKWebView(frame: <yourValue>, configuration: secondWebConfiguration)