How to embed YouTube videos into your iOS app using Swift

Last updated on: November 7, 2023

In this guide I will show you two ways to put YouTube videos in your iOS app: by using the official YouTube Player iOS Helper and with 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 to 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 Swift Package Manager (SPM).

  1. In the Project Navigator on the left side of the Xcode window, click on the project name at the top of the list to open the project settings.
  2. In the opened project settings, ensure the project name is selected in the TARGETS list.
  3. Click on the “Package Dependencies” tab at the top of the project settings area.
  4. Click the “+” button located at the bottom left of the package list.
  1. In the search bar at the top, enter the URL for the “youtube-ios-player-helper” package: https://github.com/youtube/youtube-ios-player-helper to search for it.
  2. Then, select the package from the search results to add it to your project.
  3. Click the “Add Package” button at the bottom right of the window to complete the addition of the selected package to your project.

Then, click the “Add Package” button to finalize the addition of the package to your Xcode project.

Setting up YouTube iOS Player Helper

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

If you want to have a 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:

  1. Add with drag and drop the YTPlayerView
  2. Add import YouTubeiOSPlayerHelper at the top of the file.

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

override func viewDidLoad() {
    super.viewDidLoad()
    loadVideo(videoId: "YE7VzlLtp-4")
}


private func loadVideo(videoId: String) {
    // Set playsinline = 1 to enable the video play inside the UIViewController
    let playerVars: [String: Any] = ["playsinline": 1]
    playerView.load(withVideoId: videoId, playerVars: playerVars)
}Code language: Swift (swift)

You can set different variables to the player, like playsinline which 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()
        setupPlayerView()
        // ...
    }
    
    private func setupPlayerView() {
        playerView.delegate = self
        playerView.webView?.backgroundColor = .black
        playerView.webView?.isOpaque = false
    }
    
    // ...
    
    // Uncomment the following method if you want to change the video after you loaded the first one
    /*
    private func loadAnotherVideo(videoId: String, startSeconds: Float) {
        playerView.cueVideo(byId: videoId, startSeconds: startSeconds)
    }
    */
}

extension YouTubePlayeriOSHelperViewController: YTPlayerViewDelegate {
    
    func playerViewPreferredWebViewBackgroundColor(_ playerView: YTPlayerView) -> UIColor {
        return .black
    }
    
    // Uncomment the following method if you want to use a custom loading view
    /*
    func playerViewPreferredInitialLoading(_ playerView: YTPlayerView) -> UIView? {
        let customLoadingView = UIView()
        // Create a custom loading view
        return customLoadingView
    }
    */
}Code language: Swift (swift)

2nd Method (WKWebView)

Pros
  • You don’t need any library
  • It’s almost the same as 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 an UIView in your ViewController

If you want to have a 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:

  1. Add with drag and drop the UIView and give it the name webPlayerView
  2. Add import WebKit at the top of your file.

Now, declare a WKWebView instance, create a WKWebViewConfiguration object, and set allowsInlineMediaPlayback to true.

This will enable videos to play inline within the ViewController instead of full-screen mode when you start the video.

class WebViewViewController: UIViewController {
    
    @IBOutlet weak var webPlayerView: UIView!
    
    lazy var webPlayer: WKWebView = {
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.allowsInlineMediaPlayback = true
        let webView = WKWebView(frame: webPlayerView.bounds, configuration: webConfiguration)
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }

}Code language: Swift (swift)

In the viewDidLoad method, call a custom method to set up the web player.
This setup will include adding the webPlayer as a subview of webPlayerView and setting its autoresizing properties.

override func viewDidLoad() {
    super.viewDidLoad()
    setupWebPlayer()
}

private func setupWebPlayer() {
    webPlayerView.addSubview(webPlayer)
    webPlayer.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}Code language: Swift (swift)

Next, create a method to load the video URL into the WKWebView.
This method will take a URL string as an input, convert it to a URL object, create a URLRequest, and then load it into the webPlayer.

private func loadVideoURL(_ urlString: String) {
    guard let url = URL(string: urlString) else {
        print("Invalid URL")
        return
    }
    let request = URLRequest(url: url)
    webPlayer.load(request)
}Code language: Swift (swift)

Finally, within the viewDidLoad method, and following the setupWebPlayer call, add a call to loadVideoURL, passing in the desired YouTube video URL.
This action will ensure that the video loads when the view controller is initialized.

override func viewDidLoad() {
    super.viewDidLoad()
    setupWebPlayer()
    loadVideoURL("https://www.youtube.com/embed/YE7VzlLtp-4?playsinline=1")
}Code language: Swift (swift)
You can find the final project here

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

Subscribe
Notify of
guest
18 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments