我的代码有什么问题?为什么WKWebView无法打开target =“ _ blank”的链接?我想使用默认浏览器打开在新标签中打开的链接。如何实现?
import UIKit
import WebKit
class ViewController: UIViewController,WKUIDelegate {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var activityIndicator: uiactivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
let url = "https://example.com"
let request = URLRequest(url: URL(string: url)!)
self.webView.load(request)
self.webView.addobserver(self,forKeyPath: #keyPath(WKWebView.isLoading),options: .new,context: nil)
// Page Scrolling - false or true
webView.scrollView.isScrollEnabled = false
// Open new tab links
webView.uiDelegate = self
func webView(_ webView: WKWebView,createWebViewWith configuration: WKWebViewConfiguration,for navigationaction: WKNavigationaction,windowFeatures: WKWindowFeatures) -> WKWebView? {
if let frame = navigationaction.targetFrame,frame.isMainFrame {
return nil
}
// for _blank target or non-mainFrame target
webView.load(navigationaction.request)
return nil
}
}
override func observeValue(forKeyPath keyPath: String?,of object: Any?,change: [NSKeyValueChangeKey : Any]?,context: UnsafeMutableRawPointer?) {
if keyPath == "loading" {
if webView.isLoading {
activityIndicator.startAnimating()
activityIndicator.isHidden = false
} else {
activityIndicator.stopAnimating()
activityIndicator.isHidden = true
}
}
}
}