Bhavyabhatia
Bhavyabhatia

Reputation: 57

WKWebView not loading YouTube videos in iOS app

I am developing an iOS app in which I want to show YouTube videos. This is my code

struct YouTubeView: UIViewRepresentable {
    let videoID: String

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
        configuration.allowsInlineMediaPlayback = true
        if #available(iOS 10.0, *) {
            // Ensure that media plays without requiring a user gesture.
            configuration.mediaTypesRequiringUserActionForPlayback = []
        } else {
            configuration.requiresUserActionForMediaPlayback = false
        }
        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.scrollView.isScrollEnabled = false
        return webView
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let embedURLString = "https://www.youtube.com/embed/\(videoID)?playsinline=1"
        if let url = URL(string: embedURLString) {
            let request = URLRequest(url: url)
            uiView.load(request)
        }
    }
}

struct VideoPlayerView: View {
    @EnvironmentObject var viewModel: AppViewModel
    var video: Video
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        VStack {
            YouTubeView(videoID: video.youtubeID)
                .frame(height: 200)
            
            if !video.watched {
                Button("Mark as Watched") {
                    viewModel.markVideoAsWatched(video: video)
                    presentationMode.wrappedValue.dismiss()
                }
                .padding()
            } else {
                Text("Video already watched")
                    .padding()
            }
        }
        .padding()
    }
}

I checked and the video can be embedded also, so that isn't the issue. But when I launch my app and click on the video, the app just shows a blank white screen.

Upvotes: 0

Views: 69

Answers (1)

Kiryl Famin
Kiryl Famin

Reputation: 143

You must allow arbitrary loads over HTTP/HTTPS, enabling YouTube video playback.

  1. Open (or create) Info.plist file
  2. Add NSAppTransportSecurity key of type Dictionary (sets automatically)
  3. Add NSAllowsArbitraryLoads of type Boolean (it sets to String by default, be sure to check!) and its value to YES

Info.plist

Now it should work

YouTube video

Upvotes: 0

Related Questions