1

Do YouTube URL's not work with SwiftUI's VideoPlayer. I'm attempting to use VideoPlayer(player: AVPlayer(url: URL(string: "https://www.youtube.com/watch?v=ID_HERE")!)). Is there any workarounds to this? Just shows a black screen.

enter image description here

cole
  • 1,039
  • 1
  • 8
  • 35
  • That url is just the url of the page. You probably want this: https://stackoverflow.com/q/31566835/14351818 – aheze Jul 29 '21 at 21:34

1 Answers1

2

You need to extract the YouTube video ID, try this:

import WebKit
struct WebView: 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))
    }
}



extension String {
    func extractYoutubeID() -> String? {
        let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
        
        let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let range = NSRange(location: 0, length: self.count)
        
        guard let result = regex?.firstMatch(in: self, range: range) else { return nil }
        return (self as NSString).substring(with: result.range)
    }
}



 @State private var youTubeURL: String = "YOUR VIDEO URL"
 @State private var youTubeVideoID: String = ""
 @State private var validYouTubeURL = false
  var body: some View {
       VStack {
         if validYouTubeURL {
           WebView(videoID: self.youTubeVideoID)
           .frame(width: 500, height: 500)
                }
        }.onAppear {
                if let videoID = self.youTubeURL.extractYoutubeID() {
                    self.youTubeURL = ""
                    self.youTubeVideoID = videoID
                    self.validYouTubeURL = true
                } else {
                    self.youTubeURL = ""
                }
          }
    }
SwiftUser
  • 555
  • 6
  • 17