LoginSignup
0
2

More than 3 years have passed since last update.

iOSアプリでYouTubeの動画を直接再生する方法

Last updated at Posted at 2020-12-19

背景

業務で、「これまでYouTube動画を再生するのに、一度動画をエンベッドしたウェブページを経由していたが、ネイティブ画面に直接動画を埋め込みたい」という要件が出てきたので軽く調べてみたメモです。

結論から言うとネイティブのSDKなどはないようで、WebViewを利用してエンベッドした動画を再生するという方法になるようです。

公式に薄いヘルパーはあるもののObjective-Cだし、とりあえず再生させたいだけなので自前で実装してみる。
https://developers.google.com/youtube/v3/guides/ios_youtube_helper?hl=ja

実現方法

実装方法としては動画と同じサイズになるようにレイアウトしたWebViewを配置するだけ

こんな感じでWebViewを配置。動画は16:9なので、WebViewも16:9にしておく
スクリーンショット 2020-12-19 19.18.21.png

だらっと書いてしまってますが、ポイントは以下です

  • レスポンシブに動画サイズを変更できるようにスタイル指定
  • viewport指定をしておかないと、embedされた動画がPC向けになって操作しづらい
  • scrollViewでbounceをOFFにしているが、拡大/縮小などもうちょっと制御した方がいいかも

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView! {
        didSet {
            webView.scrollView.bounces = false
        }
    }

    let vid = "M7lc1UVf-VE" // videoID
    lazy var htmlString = """
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body {
    margin: 0px;
}
.youtube {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
}
.youtube iframe {
  position: absolute;
  top: 0;
  right: 0;
  width: 100% !important;
  height: 100% !important;
}
</style>
</head>
<div class="youtube">
<iframe width="375" height="210" src="https://www.youtube.com/embed/\(vid)" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</html>
"""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        webView.loadHTMLString(htmlString, baseURL: nil)
    }
}

雑ですが、ここまででとりあえずそれっぽく再生することはできました。

サンプル

環境

  • Xcode12.3
  • iOS14.0
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2