自作のアプリでYoutubeを再生させます。
ライブラリのインストール
- アプリのプロジェクトフォルダで、CocoaPodの初期化
- → Podfileが作成される
pod init
- Podfileに、youtube-ios-player-helperを追加
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'YoutubePlayer' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for YoutubePlayer
pod 'youtube-ios-player-helper', '~> 1.0.2' # 追加
end
- CocoaPodインストールコマンド実行
pod install
- Xcodeを「プロジェクト名.xcworkspace」ファイルをダブルクリックして起動する
ViewにYoutube Playerを追加
- StoryBoardから、画面にView(UIView)を画面に設置
- ViewのクラスをYTPlayerViewに変更
- ViewControllerに、このYTPlayerViewを紐づける
ViewController
@IBOutlet weak var youtubeView: YTPlayerView!
Youtubeを再生させる
- youtube_ios_player_helperをインポートする
- YTPlayerViewDelegateを実装する
- viewDidLoadでyoutubeViewの初期化
ViewController
import UIKit
import youtube_ios_player_helper
class ViewController: UIViewController, YTPlayerViewDelegate {
@IBOutlet weak var youtubeView: YTPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.youtubeView.delegate = self
self.youtubeView.load(withVideoId: "ec3_rjH_ymE")
}
func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
self.youtubeView.playVideo()
}
}