iosswiftxcodewkwebviewwkwebviewconfiguration

mediaTypesRequiringUserActionForPlayback not working Swift


I am developing an app that access to a web page with WKWebView in Swift. This web starts playing a sound automatically. I want not allow to play the sound automatically. I would like to use something like mediaPlayBackRequieresUserAction = true but it doesn't works with WKWebView.

I am trying with something like

webConfiguration.mediaTypesRequiringUserActionForPlayback = []
webConfiguration.mediaTypesRequiringUserActionForPlayback = .all
webConfiguration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll

but it is not working, Xcode is showing me:

Cannot assign value of type '[WKAudiovisualMediaTypes].Type' to type 'WKAudiovisualMediaTypes'

The elements that are causing the audio sounds automatically are:

<audio src="audio/alarm.mp3" preload="auto" loop="true" class="alarm mp3" type="audio/mp3"></audio>
<audio src="audio/alarm2.mp3" preload="auto" loop="true" class="urgent alarm2 mp3" type="audio/mp3"></audio>

This is my WKWebView code:

    import UIKit
import WebKit

class WidgetViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

var webView : WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://danfg95glucose.azurewebsites.net/")
    let request = URLRequest(url: url!)

    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.allowsInlineMediaPlayback = false
    webConfiguration.mediaTypesRequiringUserActionForPlayback = []

    webView = WKWebView(frame: CGRect( x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 500 ), configuration: webConfiguration)
    webView.navigationDelegate = self
    webView.load(request)
        self.view.addSubview(webView)
}
    }

Sorry for my mistakes, I am new and I am learning programming. Thank you so much for every responses.


Solution

  • You only need to set mediaTypesRequiringUserActionForPlayback once. This should work.

    webConfiguration.mediaTypesRequiringUserActionForPlayback = .all
    

    You could limit it to just audio with this instead

    webConfiguration.mediaTypesRequiringUserActionForPlayback = .audio