如何在UIWebView swift中自动播放YouTube视频

时间:2017-05-17 13:54:09

标签: ios swift xcode youtube uiwebview

我在尝试自动播放我的UIWebView时遇到问题。

这是我的代码:

WebVideo.allowsInlineMediaPlayback = true
WebVideo.mediaPlaybackRequiresUserAction = false

WebVideo.loadHTMLString("<iframe width=\"\(WebVideo.frame.width)\" height=\"\(WebVideo.frame.height)\" src=\"\(thumbnail)?playsinline=1\" frameborder=\"0\" allowfullscreen & autoplay=1 &showinfo=0 &controls=0 autohide=1></iframe>", baseURL: nil)

现在这不起作用。我也试过这个代码:

 WebVideo.allowsInlineMediaPlayback = true
 WebVideo.mediaPlaybackRequiresUserAction = false

 WebVideo.loadHTMLString("<iframe width=\"\(WebVideo.frame.width)\" height=\"\(WebVideo.frame.height)\" src=\"\(thumbnail)&autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil)

它既不起作用

你能帮帮我吗,我怎么自动播放..?

2 个答案:

答案 0 :(得分:2)

我也遇到了类似的问题,最终使用了Google的帮助库

https://github.com/youtube/youtube-ios-player-helper

    let player = YTPlayerView(frame: CGRect(0,0,view.frame.width , 300))
    let dict = ["modestbranding" : 0,"controls" : 1 ,"autoplay" : 1,"playsinline" : 1,"autohide" : 1,"showinfo" : 0]
    player.loadWithVideoId("video-ID" ,playerVars: dict)
    player.delegate = self

调用此委托函数,然后

func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
    playerView.playVideo()

}

答案 1 :(得分:0)

allowsInlineMediaPlayback为我工作。但是,与此同时,Apple建议使用WKWebView代替UIWebViewStarting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView.来源:https://developer.apple.com/documentation/webkit/wkwebview