Embed youtube in SwiftUI

Updated:

🔷 YoutubeView

  • youtube videoID 와 WebKit 을 통해서 UI 에 불려지는 logic 을 작성합니다
//  YoutubeView.swift

import SwiftUI
import WebKit

struct YoutubeView: UIViewRepresentable {

let videoID: String

func makeUIView(context: Context) -> WKWebView {
  return WKWebView()
}

func updateUIView(_ uiView: WKWebView, context: Context) {
  guard let youtubeURL = URL(string: "https://www.youtube.com/embed/\(videoID)") else { return }
  uiView.scrollView.isScrollEnabled = false
  uiView.load(URLRequest(url: youtubeURL))
}
}

🔷 ContentView

  • YoutubeView component 를 불러와서 ContentView에서 확인합니다
//  ContentView.swift

import SwiftUI

struct ContentView: View {
var body: some View {
  YoutubeView(videoID: "0TD96VTf0Xs")
 }
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
  ContentView()
 }
}

📌 Portrait

스크린샷

📌 Landscape

screenShot

  • SwiftUI 특성상 default 값으로 화면을 꽉채우게 되는데, frame 크기를 설정해서 UI 에 나타낼 수 있습니다.
struct ContentView: View {
var body: some View {
  YoutubeView(videoID: "0TD96VTf0Xs")
  // maxHeight 이 UIScreen 크기의 30% 를 차지하게 설정
    .frame(minHeight: 0, maxHeight: UIScreen.main.bounds.height * 0.3)
    .cornerRadius(12)
    .padding(.horizontal, 24)

}
}

스크린샷


🗃 Reference

How to embed Youtube videos in Swift UI! - https://www.youtube.com/watch?v=CX-BdDHW0Ho

Categories:

Updated:

Leave a comment