6

Hi I am working on iOS 10 with Swift3 right now.

My scenario is to autoplay a youtube video inline using WKWebView. I set the config's mediaPlaybackRequiresUserAction to false in order to enable the video autoplay, as suggested by Apple Dev Docs.

However this config does not seem to work, the video loaded correctly, but you have to press the play button to make it actually play.

Any ideas? Thanks :)

let config = WKWebViewConfiguration()
config.requiresUserActionForMediaPlayback = false
config.allowsInlineMediaPlayback = true
let webView = WKWebView(frame: self.topView.bounds, configuration: config)
webView.addObserver(self, forKeyPath: self.webViewLoadingKey, options: .new, context: nil)
RainCast
  • 4,134
  • 7
  • 33
  • 47
  • Were you able to autoplay Youtube video inline using WKWebView? –  Dec 17 '17 at 15:38
  • No, I think there are some bugs in WKWebView, I remember I ended up filed a bug to Swift. Not sure if they've got it fixed. You can try and let us know. Thanks. – RainCast Dec 19 '17 at 03:00

2 Answers2

5

use this for iOS10:

var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes { get set }

Razor
  • 91
  • 1
  • 4
3

The reason why that code not work is the .mediaPlaybackRequiresUserAction deprecated from iOS 10.0 enter image description here

As no alternative property provided, it seems the task using WKWebViewcannot be done at current stage. However if you just want to auto play H5 video, UIWebView could be your choice

func initPureWeb(){
    let web = UIWebView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    web.backgroundColor = UIColor.clear
    web.isOpaque = false
    self.view.addSubview(web)
    web.mediaPlaybackRequiresUserAction = false
    let videoHtml = "<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'200', height:'200', videoId:'bHQqvYy5KYo', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
    web.loadHTMLString(videoHtml, baseURL: Bundle.main.resourceURL)
}
Chen Wei
  • 521
  • 4
  • 10
  • Thanks for your answer. I couldn't use UIWebView, because it brought a lot of performance issues after migrated to iOS10. My code is actually to remove UIWebView, and replace it with WKWebView. Ironically... :D – RainCast Sep 21 '16 at 07:32
  • also, requiresUserActionForMediaPlayback one is not deprecated. – RainCast Sep 21 '16 at 07:34