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)
use this for iOS10:
var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes { get set }
The reason why that code not work is the .mediaPlaybackRequiresUserAction
deprecated from iOS 10.0
As no alternative property provided, it seems the task using WKWebView
cannot 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With