Reputation: 57
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
Reputation: 143
You must allow arbitrary loads over HTTP/HTTPS, enabling YouTube video playback.
Info.plist
fileNSAppTransportSecurity
key of type Dictionary (sets automatically)NSAllowsArbitraryLoads
of type Boolean (it sets to String by default, be sure to check!) and its value to YES
Now it should work
Upvotes: 0