关于iOS:如何在WKWebView中自动播放YouTube视频?

How to autoplay youtube video in WKWebView?

我写了一个代码在WKWebView中播放youtube视频。我想在加载屏幕时自动播放视频,并且内联视频也不应在新屏幕中播放。以下是我的代码。

1
2
3
4
5
6
7
8
9
10
 @IBOutlet weak var myPlayer: WKWebView!
 override func viewDidLoad() {
    super.viewDidLoad()

    if let videoURL:URL = URL(string:
   "https://www.youtube.com/embed/695PN9xaEhs?playsinline=1") {
    let request:URLRequest = URLRequest(url: videoURL)
    myPlayer.load(request)
  }
 }

我已经在"界面"构建器中设置了WKWebView的配置。

Interface


使用iFrame在WKWebview上加载视频并编写脚本以自动播放视频。请参见以下代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class YouTubeVideoPlayerVC: UIViewController {

    @IBOutlet weak var videoPlayerView: WKWebView!
    var videoURL:URL!  // has the form"https://www.youtube.com/embed/videoID"
    var didLoadVideo = false

    override func viewDidLoad() {
        super.viewDidLoad()
        videoPlayerView.configuration.mediaTypesRequiringUserActionForPlayback = []
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // Size of the webView is used to size the YT player frame in the JS code
        // and the size of the webView is only known in `viewDidLayoutSubviews`,
        // however, this function is called again once the HTML is loaded, so need
        // to store a bool indicating whether the HTML has already been loaded once
        if !didLoadVideo {
            videoPlayerView.loadHTMLString(embedVideoHtml, baseURL: nil)
            didLoadVideo = true
        }
    }

    var embedVideoHtml:String {
        return"""
        <!DOCTYPE html>
        <html>
        <body>
        <!-- 1. The &lt;iframe> (and video player) will replace this  tag. -->
       

       
        var tag = document.createElement('script');

        tag.src ="https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        var player;
        function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
        playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
        height: '\\(videoPlayerView.frame.height)',
        width: '\\(videoPlayerView.frame.width)',
        videoId: '\\(videoURL.lastPathComponent)',
        events: {
        'onReady': onPlayerReady
        }
        });
        }

        function onPlayerReady(event) {
        event.target.playVideo();
        }
       
        </body>
        </html>
       """
    }
}

有关详细信息,请参见以下文章。在带有iOS 11的WKWebView中自动播放YouTube视频


确保在创建Web视图时通过配置。像这样:

1
2
3
4
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = []
let webView = WKWebView(frame: .zero, configuration: configuration)

mediaTypesRequiringUserActionForPlayback

1
2
//Determines which media types require a user gesture to begin playing.
var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes

只需将此属性设置为空数组即可自动播放。