Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS10: Auto play not working on WKWebView (requiresUserActionForMediaPlayback = false)

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)
like image 685
RainCast Avatar asked Sep 20 '16 22:09

RainCast


2 Answers

use this for iOS10:

var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes { get set }

like image 75
Razor Avatar answered Nov 15 '22 04:11

Razor


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)
}
like image 43
Chen Wei Avatar answered Nov 15 '22 03:11

Chen Wei