捕获视频网址WKWebView

时间:2016-06-29 15:37:45

标签: swift swift2 wkwebview

嗨,我在swift中打开一个来自WKWebView的视频,它自动打开这个视频页面,无论如何我捕获视频链接并使用这个视频的网址?

Video

1 个答案:

答案 0 :(得分:0)

您应该实现委托WKNavigationDelegate并定义函数decisionPolicyForNavigationAction,例如:

class ViewController: UIViewController, WKNavigationDelegate {
...

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    webView = WKWebView(frame: CGRect(x: 0, y: 50, width: 100, height: 100))
    webView.navigationDelegate = self
    webView.loadRequest(NSURLRequest(URL: NSURL(string: "https://www.example.com")!))
    view.addSubview(webView)
}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    let path = navigationAction.request.URL?.absoluteString
    if let path = path {
        if path.rangeOfString("mp4") != nil {
            // This is video link, don't let iOS open video
            decisionHandler(.Cancel)
            print("Process video \(path)")
            return
        }
    }
    // Any other link should be handled by WKWebView
    decisionHandler(.Allow)
}

检测视频链接是否包含路径中的mp4或您要检测的其他扩展名或路径,然后自行处理。