Wkwebview 对 youtube 链接没有反应

Wkwebview doesn't react to youtube-links

我目前正在用原生 tabBar 包装一个网站,它使用 didCommitNavigation/didFinishNavigationdidStartProvisionalNavigation/didFailProvisionalNavigation[= 处理导航22=] 根据单击的 link 更改选项卡。当涉及网站域内的 links 时,这工作得很好,但是当单击 Youtube-link.[=12= 时,webview 似乎没有任何反应]

I thought it might have to do with my security settings, but it seems like it doesn't

这是我的主viewcontroller,也是唯一的viewcontroller项目:

import UIKit
import WebKit

class MainViewController: UIViewController, UITabBarDelegate, UIScrollViewDelegate, WKNavigationDelegate {

@IBOutlet weak var noConnectionLabel: UILabel!
@IBOutlet weak var tabBar: UITabBar!
@IBOutlet weak var statusImage: UIImageView!
@IBOutlet weak var viewForWeb: UIView!
@IBOutlet weak var retryButton: UIButton!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!

let statusColors: [UIColor] = UIColor.getStatusColors()

var currentIndex: Int = 0

var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView = WKWebView(frame: CGRectMake(0, 0, viewForWeb.frame.size.width, viewForWeb.frame.size.height))

    viewForWeb.addSubview(webView)
    webView.scrollView.delegate = self
    webView.navigationDelegate = self


    loadingIndicator.startAnimating()
    tabBar.delegate = self

    tabBar.barTintColor = UIColor.tabBarBackgroundColor()
    tabBar.tintColor = UIColor.iconColor()
    for item in tabBar.items! {
        item.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3)
        item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.iconColor()], forState:.Normal)
        item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.iconColor()], forState:.Selected)
    }
    tabBar.selectionIndicatorImage = UIImage(named: "news-tab")
    tabBar.selectedItem = tabBar.items![0]

    statusImage.backgroundColor = UIColor.newsColor()

    webView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    webView.loadRequest(NSURLRequest(URL: startURLs[0]))
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func retryConnection(sender: AnyObject) {
    webView.loadRequest(NSURLRequest(URL: failedNavigationURL))
    noConnectionLabel.hidden = true
    retryButton.hidden = true
    loadingIndicator.hidden = false

}


func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print(webView.URL!)
}

func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
    print(webView.URL!)
    for view in views {
        if webView.URL!.absoluteString.lowercaseString.rangeOfString(view) != nil {
            tabBar.selectionIndicatorImage = UIImage(named: "\((view as NSString).substringToIndex(view.characters.count - 1))-tab")!
            if tabBar.selectedItem != tabBar.items![views.indexOf(view)!] {
                currentIndex = views.indexOf(view)!
                tabBar.selectedItem = tabBar.items![views.indexOf(view)!]
                statusImage.backgroundColor = statusColors[tabBar.items!.indexOf(tabBar.selectedItem!)!]
                viewForWeb.hidden = true
            }
        }
    }
}

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    loadingIndicator.stopAnimating()
    statusImage.backgroundColor = statusColors[tabBar.items!.indexOf(tabBar.selectedItem!)!]
    loadingIndicator.hidden = true
    noConnectionLabel.hidden = true
    retryButton.hidden = true
    viewForWeb.hidden = false
}

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    failedNavigationURL = NSURL(string: error.userInfo[NSURLErrorFailingURLStringErrorKey]! as! NSString as String)!
    statusImage.backgroundColor = UIColor.clearColor()
    viewForWeb.hidden = true
    noConnectionLabel.hidden = false
    retryButton.hidden = false
    loadingIndicator.hidden = true
}


func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

    let indexOfItem = tabBar.items!.indexOf(item)!

    if indexOfItem != currentIndex {
        tabBar.selectionIndicatorImage = UIImage(named: "\(item.title!.lowercaseString)-tab")
        statusImage.backgroundColor = statusColors[indexOfItem]
        webView.evaluateJavaScript("document.open();document.close()", completionHandler: nil)
        webView.loadRequest(NSURLRequest(URL: startURLs[indexOfItem]))
        currentIndex = indexOfItem
        loadingIndicator.hidden = false
        loadingIndicator.startAnimating()
        viewForWeb.hidden = true
    }
}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return nil
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView.contentOffset.x>0 || scrollView.contentOffset.x<0 {
        scrollView.contentOffset.x = 0
    }
}

为了匿名,我省略了一些数组,但我认为它仍然是可读的。需要澄清的是,print()s 仅打印网站域内的 URL,单击 Yotube-links.

时不显示任何内容

是的,我也遇到了同样的问题。发生这种情况是因为 wkwebview 代表在 in-page javascript 操作中没有 return 任何回调,而在 youtube 的情况下实际发生了什么。

不过,你可以使用KV Observer来解决。

在您的 viewDidLoad 或任何初始化函数中写入此代码:

webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)

在此函数中获取回调:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 
  {
    if keyPath! == "URL" {
      getYourVideoURL = (webView.url?.absoluteString)!
    }
  }

记得在 viewDidDisappear 或任何您想停止接收回调的地方移除观察者。