Wkwebview对youtube-links没有反应

时间:2016-09-05 08:06:49

标签: ios swift wkwebview

我目前正在原生tabBar中包装网站,并使用 didCommitNavigation / didFinishNavigation didStartProvisionalNavigation / didFailProvisionalNavigation 来处理导航,以根据链接更改标签点击。当涉及到网站域内的链接时,这很好用,但是当点击Youtube链接时,似乎没有任何反应来自webview。

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

这是我的主视图控制器,它是项目的唯一一个视图控制器:

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()仅打印网站域内的URL,单击Yotube链接时没有任何内容。

1 个答案:

答案 0 :(得分:3)

是的,我也面临同样的问题。之所以发生这种情况,是因为wkwebview代表在页面javascript操作中没有返回任何回调,在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中的观察者或者您想要停止获取回调的位置。