TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

[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      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.