2017-08-14 58 views
1

我是Swift的新手,我正在製作一個可以顯示youtube視頻的webview應用。我的問題是我不希望我的用戶去其他網址或類似的東西。我想讓我的應用加載youtube.com。我使用的是HTML而不是URL,因爲我可以告訴我的webview它會有什麼樣的高度和寬度。如何使webview只加載特定的網站,如youtube?

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> 

回答

0

你可以嘗試使用的UIWebViewDelegate

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 
    } 
} 

shouldStartLoadWith委託方法一定要設置UIViewControllerUIWebView代表在viewDidLoad方法:

override func viewDidLoad() { 
    super.viewDidLoad() 

    myWebView.delegate = self 
} 
相關問題