现在如何使用iOS播放YouTube视频?

时间:2018-11-15 05:59:40

标签: ios swift avfoundation

我正在上一门在线课程,该课程显示了如何播放URL中的视频。但这始终是bunny one。我一直在寻找如何播放YouTube视频,发现它们曾经使用过UIWebView。由于已被弃用,现在我该如何播放它们。这就是我的代码的样子。

import UIKit
import AVKit
import AVFoundation

class CourseDetailVC: UIViewController {
    @IBOutlet weak var descriptionTextView: UITextView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var authorButton: UIButton!
    @IBOutlet weak var backgroundImage: UIImageView!

    var course: Courses.Course?

    @IBAction func playURLVideo() {
        guard let videoURL = URL(string: course?.videoUrl ?? "") else { return }
        let player = AVPlayer(url: videoURL)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
    }

我只有一个按钮。当我按它时,我想播放一个YouTube视频。现在,这适用于一只兔子。我将如何播放这个YouTube video

按下按钮后的屏幕截图

enter image description here

更新代码

 @IBAction func playButtonPress() {
    // Create Video player
    var mywkwebview: WKWebView?
    let mywkwebviewConfig = WKWebViewConfiguration()

    mywkwebviewConfig.allowsInlineMediaPlayback = true
    mywkwebview = WKWebView(frame: self.view.frame, configuration: mywkwebviewConfig)

    let myURL = URL(string: "https://www.youtube.com/embed/JePnQ1gSagc?playsinline=1?autoplay=1")
    let youtubeRequest = URLRequest(url: myURL!)

    mywkwebview?.load(youtubeRequest)

    guard let webView = mywkwebview else { return }
    self.view.addSubview(webView)

}

1 个答案:

答案 0 :(得分:0)

这是WKWebView

的解决方案

由于YouTube具有使用https://www.youtube.com/embed/<videoId>格式的URL无需任何滚动功能即可在网络视图中全屏加载任何视频的功能。

上面给定的视频ID为(https://www.youtube.com/watch?v=1roy4o4tqQM)-[1roy4o4tqQM]

mywkwebviewConfig.allowsInlineMediaPlayback = true
mywkwebview = WKWebView(frame: self.view.frame, configuration: mywkwebviewConfig)
let myURL = URL(string: "https://www.youtube.com/embed/1roy4o4tqQM?playsinline=1?autoplay=1")
var youtubeRequest = URLRequest(url: myURL!)
mywkwebview.load(youtubeRequest)

更新代码:

@IBAction func playURLVideo() {

  var mywkwebview: WKWebView?
  let mywkwebviewConfig = WKWebViewConfiguration()

  mywkwebviewConfig.allowsInlineMediaPlayback = true
  mywkwebview = WKWebView(frame: self.view.frame, configuration: mywkwebviewConfig)

  let myURL = URL(string: "https://www.youtube.com/embed/1roy4o4tqQM?playsinline=1?autoplay=1")
  var youtubeRequest = URLRequest(url: myURL!)

  mywkwebview.load(youtubeRequest)
}

您需要在嵌入?autoplay=1的末尾添加URL