UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

[Solved] How to play a YouTube video in SwiftUI ?

Forums > SwiftUI

I am using the below code and it seems to show a black screen in middle, how can i make this work, thanks

struct CollectionView: View {
    @State var player = AVPlayer(url: URL(string: "https://www.youtube.com/watch?v=")!)
var body: some View {
    ZStack {
        Image("cover")
            .resizable().opacity(0.2)
        VStack {
            Text("Demo Song")
                .font(.title)
        VideoPlayer(player: player)
                           .frame(width: 400,
                                  height: 300,
                                  alignment: .center)

        }
    }
}

}

1      

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 demoURL = URL(string: "https://www.youtube.com/embed/\(videoId)") else { return }
        uiView.scrollView.isScrollEnabled = false
        uiView.load(URLRequest(url: demoURL))
    }
}

struct CollectionView: View {
    var ids = ["xxxxxxxxx", "xxxxxxxxxx", "xxxxxxxxx"]
    var body: some View {
        ZStack {
            Image("cover")
                .resizable().opacity(0.2)
            ScrollView(showsIndicators: false) {
                VStack {
                    Text("Demo")
                        .font(.title)

                    ForEach(ids, id:\.self) {idData in
                        YouTubeView(videoId: idData)
                            .frame(width: 300, height: 300)
                            .padding()
                    }

                }
            }

        }
    }
}

1      

@sasha  

Guys there is much easier way to embed a video from YouTube

https://github.com/SvenTiigi/YouTubePlayerKit use this

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.