2

I have a YouTube video embedded in a UIWebView. It plays just fine. When I segue to a different View Controller without pausing the video, however, it continues to play the audio. How do I stop it?

Code:

func loadYouTubeVideo() {

    let youTubeLink: String = "https://www.youtube.com/embed/ac_om5HCjvg"
    let width = 300
    let height = 200
    let frame = 50
    let html:NSString = "<iframe width=\(width) height=\(height) src=\(youTubeLink) frameborder=\(frame) allowfullscreen></iframe>"
    self.youTubeWebView.loadHTMLString(html as String, baseURL: nil)

}

I need a Swift answer. I've tried using Objective-C, but it doesn't translate unless I'm doing it wrong:

 let script = "var videos = document.querySelectorAll(\"video\"); for (var i = videos.length - 1; i >= 0; i--) { videos[i].pause(); };"
 youTubeWebView.stringByEvaluatingJavaScriptFromString(script)
JAL
  • 41,701
  • 23
  • 172
  • 300
swiftyboi
  • 2,965
  • 4
  • 25
  • 52
  • 1
    Possible duplicate of [Stop video in UIWebView](http://stackoverflow.com/questions/7038100/stop-video-in-uiwebview) – JAL Jan 20 '16 at 21:19
  • Unfortunately, those answers don't work for me. It could be that it's in Objective-C, and I'm working in Swift. – swiftyboi Jan 20 '16 at 21:30
  • What do you mean they don't work? Have you tried translating them into Swift? – JAL Jan 20 '16 at 21:45

3 Answers3

3

Try this

  override func viewWillDisappear(animated: Bool) {
        webView.loadHTMLString(nil, baseURL: nil)
    }

Let me know if it works

Kerby Jean
  • 207
  • 2
  • 12
  • `loadHTMLString` requires a non-optional string HTML string, you can't pass in nil. – JAL Jan 21 '16 at 20:58
2

If you don't care about the user resuming the video from the beginning after navigating away from the view, have the webview load an empty page:

webView.loadHTMLString("<html><head></head><body></body></html>", baseURL: nil)

If you do this, you will have to load your video again in viewWillAppear.

JAL
  • 41,701
  • 23
  • 172
  • 300
0

I used the following to stop my audio:

webView.loadHTMLString("", baseURL: nil) 
slfan
  • 8,950
  • 115
  • 65
  • 78