mediaTypesRequiringUserActionForPlayback 不工作 Swift

mediaTypesRequiringUserActionForPlayback not working Swift

我正在 Swift 中开发一个使用 WKWebView 访问网页的应用程序。该网站开始自动播放声音。我不想让声音自动播放。我想使用类似 mediaPlayBackRequieresUserAction = true 的东西,但它不适用于 WKWebView。

我正在尝试

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

但它不起作用,Xcode 向我显示:

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

自动引起音频声音的元素是:

<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>

这是我的 WKWebView 代码:

    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)
}
    }

抱歉我的错误,我是新手,正在学习编程。非常感谢您的每一个回复。

您只需设置一次mediaTypesRequiringUserActionForPlayback。这应该有效。

webConfiguration.mediaTypesRequiringUserActionForPlayback = .all

您可以改为将其限制为仅音频

webConfiguration.mediaTypesRequiringUserActionForPlayback = .audio

太令人沮丧了。 我发现在运行时更改 mediaTypesRequiringUserActionForPlayback 完全被忽略了。 webView 配置仍然有 .none 作为它的值 ☹️

所以在我的 ViewController 的 viewDidLoad() 中我做了这个

private func workaroundAppleUserActionForPlaybackBug() -> WKWebView
{
    // you can set the value in the configuration, but it doesn't actually change!
    // even setting these values in IB doesn't work, it's always ZERO (meaning auto playback)
    //
    let frame = self.webView.frame
    let configuration = self.webView.configuration
    configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.all
    
    return WKWebView(frame: frame, configuration: configuration)
}

override func viewDidLoad()
{
    super.viewDidLoad()
    
    self.webView = workaroundAppleUserActionForPlaybackBug()
}