How to embed YouTube videos into your iOS app using Swift

How to embed YouTube videos into your iOS app using Swift

In this tutorial, I’m going to show you how to embed a youtube video in your iOS app with three different methods, using the official library (YouTube Player iOS Helper), a 3rd party library called XCDYouTubeKit, and WKWebView.

1st Method (YouTube Player iOS Helper)

Pros
  • Official library provided by YouTube
Cons
  • Doesn’t get updated very often
  • Cannot play private videos, but it can play unlisted videos
  • Nearly identical of a player embedded on a webpage in a mobile browser

YouTube Player iOS Helper is the official way to embed a youtube video in your iOS app. It’s a recommended method if you don’t want to display a lot of videos in your app.

Adding the library

In this example, we are going to add the YouTube Player iOS Helper library into our project using Cocaopods.

Open your Podfile with your favorite text editor (e.g Visual Studio Code) and add pod 'youtube-ios-player-helper'

Then, run pod update in the terminal

Add a UIView in your ViewController and under the Custom Class, in the Class field, add YTPlayerView

If you want to have 16:9 aspect ratio in your YTPlayerView, set the top, leading and trailing equals to Superview (or Safe Area) of your ViewController

Make the width of the YTPlayerView equal to the width of the ViewController

Add Aspect Ratio to the YTPlayerView

…and set the Multiplier to 16:9

Next, in the swift file of your ViewController, add with drag and drop the YTPlayerView and add import youtube_ios_player_helper at the top of your file.

Now, add a video to the player using the id of the video:

override func viewDidLoad() {
    super.viewDidLoad()
    
    playerView.load(withVideoId: "YE7VzlLtp-4", playerVars: ["playsinline": "1"])
    
}

You can set different variables to the player, like playsinline that allows you to play the video inside the ViewController instead of full-screen mode when you start the video.

If you want more customization, like background color or custom loading view, add the YTPlayerViewDelegate to your class:

class YouTubePlayeriOSHelperViewController: UIViewController {
    @IBOutlet var playerView: YTPlayerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        playerView.delegate = self
        
        // ...
    }
}

extension YouTubePlayeriOSHelperViewController: YTPlayerViewDelegate {
    func playerViewPreferredWebViewBackgroundColor(_ playerView: YTPlayerView) -> UIColor {
        return UIColor.black
    }
    
    func playerViewPreferredInitialLoading(_ playerView: YTPlayerView) -> UIView? {
//        let customLoadingView = UIView()
//        Create a custom loading view
//        return customLoadingView
    }
}

2nd Method (3rd Party Library XCDYouTubeKit)

Pros
  • Better performance
Cons

In this method, we’re going to use the 3rd party library XCDYouTubeKit, made by 0xced, to embed our YouTube video into our app.

Adding the XCDYouTubeKit library

In this example, we are going to add the XCDYouTubeKit library into our project using Cocaopods.

Open your Podfile with your favorite text editor (e.g Visual Studio Code) and add pod 'XCDYouTubeKit'

Then, run pod update in the terminal

Add a UIView in your ViewController

If you want to have 16:9 aspect ratio in your UIView, set the top, leading and trailing equals to Superview (or Safe Area) of your ViewController

Make the width of the UIView equal to the width of the ViewController

Add Aspect Ratio to the UIView

…and set the Multiplier to 16:9

Next, in the swift file of your ViewController, add with drag and drop the UIView and give it the name playerViewContainer.

Declare the AVPlayer, initialize the AVPlayerViewController and at the top of your file, add import XCDYouTubeKit and import AVKit

import UIKit
import AVKit
import XCDYouTubeKit

class XCDYouTubeKitViewController: UIViewController {
    
    @IBOutlet var playerViewContainer: UIView!
    
    var playerView: AVPlayer!
    
    let playerViewController = AVPlayerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         // ...

    }
}

To play a video, use the video id, set the quality of the video you want to play, initialize an AVPlayer and add it to the AVPlayerViewController

import UIKit
import AVKit
import XCDYouTubeKit

class XCDYouTubeKitViewController: UIViewController {
    
    @IBOutlet var playerViewContainer: UIView!
    
    var playerView: AVPlayer!
    
    let playerViewController = AVPlayerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let videoId = "YE7VzlLtp-4"
        
        let youtubeClient = XCDYouTubeClient.default()
        youtubeClient.getVideoWithIdentifier(videoId) { video, _ in
            guard let ytVideo = video else { fatalError("Couldn't get the video from video id") }
            
            // YouTube has removed 1080p mp4 videos
            guard let streamURL = (ytVideo.streamURLs[XCDYouTubeVideoQualityHTTPLiveStreaming] ??
                ytVideo.streamURLs[XCDYouTubeVideoQuality.HD720.rawValue] ?? ytVideo.streamURLs[XCDYouTubeVideoQuality.medium360.rawValue] ?? ytVideo.streamURLs[XCDYouTubeVideoQuality.small240.rawValue]) else { fatalError("Couldn't get URL for this quality") }
            self.playerView = AVPlayer(url: streamURL)
            
            self.playerViewController.player = self.playerView
            self.addChild(self.playerViewController)
            
            // Add your view Frame
            self.playerViewController.view.frame = self.playerViewContainer.bounds
            
            // Add sub view in your view
            self.playerViewContainer.addSubview(self.playerViewController.view)
            
            // Start video when you open the ViewController
//            self.playerView.start()
            
            // Press play button to start the video
            self.playerView.pause()
        }
    }
}

3rd Method (WKWebView)

Pros
  • You don’t need any library
  • It’s almost the same with the official library
Cons
  • Cannot play private videos, but it can play unlisted videos
  • You have to create the WKWebView programmatically to work properly

Adding YouTube Player with WKWebView into our app

Add a UIView in your ViewController

If you want to have 16:9 aspect ratio in your UIView, set the top, leading and trailing equals to Superview (or Safe Area) of your ViewController

Make the width of the UIView equal to the width of the ViewController

Add Aspect Ratio to the UIView

…and set the Multiplier to 16:9

Next, in the swift file of your ViewController, add with drag and drop the UIView and give it the name webPlayerView and add import WebKit at the top of your file.

Then, select your project in the Project Navigator, choose your app in Targets, select Build Phases and under the Link Binary With Libraries, press the + button, and add the WebKit.framework into your project.

Now, go back to the swift file, declare a WKWebView, create a WKWebViewConfiguration, and use the allowsInlineMediaPlayback to play the video inside the ViewController instead of full-screen mode when you start the video.

Next, create a WKWebView giving the frame of the UIView we created before, and make a URLRequest

import UIKit
import WebKit

class WebView: UIViewController {
    @IBOutlet var webPlayerView: UIView!
    
    var webPlayer: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.allowsInlineMediaPlayback = true
        
        DispatchQueue.main.async {
            self.webPlayer = WKWebView(frame: self.webPlayerView.bounds, configuration: webConfiguration)
            self.webPlayerView.addSubview(self.webPlayer)
            
            guard let videoURL = URL(string: "https://www.youtube.com/embed/YE7VzlLtp-4?playsinline=1") else { return }
            let request = URLRequest(url: videoURL)
            self.webPlayer.load(request)
        }
    }
}

Don’t forget to add the ?playsinline=1 parameter at the end of your embedded video link, so the allowsInlineMediaPlayback to work correctly.

You can find the final project here

If you have any questionsplease feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments