我是 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>
最佳答案
您可以尝试使用 UIWebViewDelegate
的 shouldStartLoadWith
委托(delegate)方法
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
委托(delegate):
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
}
关于html - 如何让 webview 只加载特定的网站,比如 youtube?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45681085/