In my work, I had a requirement that "I used to play YouTube videos via a web page that once embedded the video, but I want to embed the video directly on the native screen", so I took a quick look at it. ..
From the conclusion, it seems that there is no native SDK etc., and it seems that it will be a method to play the embedded video using WebView.
Although there is an officially thin helper, it is Objective-C, and I just want to play it for the time being, so I will implement it myself. https://developers.google.com/youtube/v3/guides/ios_youtube_helper?hl=ja
As an implementation method, just place a WebView laid out so that it is the same size as the video
Place the WebView like this. Since the video is 16: 9, WebView should also be 16: 9.
I wrote it loosely, but the points are as follows
--Style specification so that you can change the video size responsively --If you do not specify the viewport, the embed video will be for PC and it will be difficult to operate. --Bounce is turned off in scrollView, but it may be better to control enlargement/reduction etc.
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)
}
}
It's rough, but I was able to play it like that for the time being.
https://github.com/satorun/EmbedYouTubeVideos/tree/main
Recommended Posts