我正在使用Swift 4进行网络视图。 我正在加载本地html文件,这些页面中有一些指向其他网站的链接,但是一旦单击其中任何一个,我都希望将它们加载到safari或默认浏览器中,而不是WebView(浏览器)中。
我的webView称为“浏览器”
这是我的ViewController.swift代码:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var browser: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let htmlpath = Bundle.main.path(forResource: "kusrc/index", ofType: "html")
let url = URL(fileURLWithPath: htmlpath!)
let request = URLRequest(url: url)
browser.load(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
有人可以帮我吗? google中的大多数结果都不是我所需要的...
是否有可能制作if语句,询问是否stringprefix =“ http://或https://”,然后打开Safari,否则打开“浏览器”
答案 0 :(得分:1)
我认为您正在寻找此委托方法:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
UIApplication.shared.open(url)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
如果您想根据URL
进行区分,可以使用URLComponents
将URL分成不同的部分。
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if components?.scheme == "http" || components?.scheme == "https" {
// insert your code here
}
//编辑(更为详细):
WebKit
:import WebKit
WKNavigationDelegate
后面,使您的类符合class ViewController: UIViewController, WKNavigationDelegate
。browser.navigationDelegate = self
最后一堂课的样子:WKWebView open links in Safari
这是关于该主题的非常不错的教程:https://www.hackingwithswift.com/example-code/wkwebview/how-to-control-the-sites-a-wkwebview-can-visit-using-wknavigationdelegate