BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

[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)

        }
    }
}

}

   

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()
                    }

                }
            }

        }
    }
}

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn 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.