Embed YouTube video in WKWebView

  1. Get the youtube video URL
  2. Add WKWebView to your UIView using code. Somehow it works better when added through code. Your resulting code will look like this
import UIKit
import WebKit
class ViewController: UIViewController {
    @IBOutlet weak var videoPlayer: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        DispatchQueue.main.async {
            let webPlayer = WKWebView(frame: self.videoPlayer.bounds, configuration: webConfiguration)
            self.videoPlayer.addSubview(webPlayer)
        }
    }
}

3. Now create a request with your youtube URL and add ?playsinline=1 this will play video inline. The resulting code will look like this

import UIKit
import WebKit
class ViewController: UIViewController {
    @IBOutlet weak var videoPlayer: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()        
        let webConf = WKWebViewConfiguration()
        webConf.allowsInlineMediaPlayback = true
        DispatchQueue.main.async {
            let webPlayer = WKWebView(frame: self.videoPlayer.bounds, configuration: webConf)
            self.videoPlayer.addSubview(webPlayer)
            
            guard let videoURL = URL(string: "https://<your URL>?playsinline=1") else { return } //works with vimeo as well
            let request = URLRequest(url: videoURL)
            webPlayer.load(request)
        }
    }
}

To get the best results you should keep the frame of WKWebView in 16:9 ratio.

A pat on the back !!