【问题标题】:How to make webview only load specific website like youtube?如何让 webview 只加载特定的网站,比如 youtube?
【发布时间】:2018-01-22 16:19:01
【问题描述】:
我是 Swift 新手,我正在制作一个带有 webview 的应用程序,可以显示 youtube 视频。我的问题是我不希望我的用户转到另一个 url 或类似的东西。我想让我的应用加载 youtube.com。我使用 HTML 而不是 URL,因为我可以告诉我的 webview 它的高度和宽度。
HTML 代码:
<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"http://www.youtube.com/embed/" + vid.videoId + "?showinfo=0&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>
【问题讨论】:
标签:
html
swift
webview
youtube
【解决方案1】:
您可以尝试使用UIWebViewDelegate 的shouldStartLoadWith 委托方法
extension UIViewController: UIWebViewDelegate {
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.url?.absoluteString ?? ""
print("WebView shouldStartLoadWithRequest url -> \(url)")
if !url.contains("youtube.com") {
// avoid loading strange urls..
// manage error as you need..
webView.stopLoading()
return false
}
return true
}
}
记得在viewDidLoad方法中设置UIViewController为UIWebView委托:
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
}