Прокрутка вкладок, содержащих короткометражки YouTube, приводит к воспроизведению неправильного видеоIOS

Программируем под IOS
Ответить
Гость
 Прокрутка вкладок, содержащих короткометражки YouTube, приводит к воспроизведению неправильного видео

Сообщение Гость »


I have a YouTube view that displays a YouTube video in full screen. The struct is made to auto play when it appears, pause on tap, and has other features. When I put a bunch of these views in a vertical tab view and scroll through sometimes the wrong video that is not showing plays instead of the one that is currently displayed.
But sometimes it works just fine. But in most cases if I am scrolling down the next video will play and I can hear its audio while the current video is paused. Or if I am scrolling up then the previous video will play while the current video is paused. The 2 things that control whether the video auto plays are: in the onAppear isPlaying is toggled to true (this only works is the video has already been rendered and the user scrolls back to it), the second is in the web view did Finish function where

Код: Выделить всё

webView.evaluateJavaScript("clickReady()", completionHandler: nil)
is run to auto play the video when the video is ready.
But this second case only runs

Код: Выделить всё

if self.parent.viewIsShowing {
which is another bool that is true when the view is showing and then false when the view disappears. Because of this I'm not sure why the wrong video that isn't showing in the tab view plays and not the currently displayed one.

Код: Выделить всё

import SwiftUI
import WebKit
import UIKit

struct AllVideoView: View {
@State private var selected = ""
@State private var arr = ["-q6-DxWZnlQ", "Bp3iu47RRJQ", "lXJdgDjw1Ks", "It3ecCpuzgc", "7WNJjr8QM1w"]
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea([.bottom, .top])
TabView(selection: $selected){
ForEach(arr, id: \.self){ id in
SingleVideoView(link: id).tag(id)
}
.rotationEffect(.init(degrees: -90))
.frame(width: widthOrHeight(width: true), height: widthOrHeight(width: false))
}
.offset(x: -10.5)
.frame(width: widthOrHeight(width: false), height: widthOrHeight(width: true))
.rotationEffect(.init(degrees: 90))
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
}
}

struct SingleVideoView: View {
let link: String
@State private var viewIsShowing = false
@State private var isVideoPlaying = false
var body: some View {
ZStack {
Color.black

SmartReelView(link: link, isPlaying: $isVideoPlaying, viewIsShowing: $viewIsShowing)

Button("", action: {}).disabled(true)

Color.gray.opacity(0.001)
.onTapGesture {
isVideoPlaying.toggle()
}

}
.ignoresSafeArea()
.onDisappear {
isVideoPlaying = false
viewIsShowing = false
}
.onAppear {
viewIsShowing = true
isVideoPlaying = true
}
}
}

struct SmartReelView: UIViewRepresentable {
let link: String
@Binding var isPlaying: Bool
@Binding var viewIsShowing: Bool

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

func makeUIView(context: Context) -> WKWebView {
let webConfiguration = WKWebViewConfiguration()
webConfiguration.allowsInlineMediaPlayback = true
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = context.coordinator

let userContentController = WKUserContentController()

webView.configuration.userContentController = userContentController

loadInitialContent(in: webView)

return webView
}

func updateUIView(_ uiView: WKWebView, context: Context) {
var jsString = """
isPlaying = \((isPlaying) ? "true"  : "false");
watchPlayingState();
"""
uiView.evaluateJavaScript(jsString, completionHandler: nil)
}

class Coordinator: NSObject, WKNavigationDelegate {
var parent: SmartReelView

init(_ parent: SmartReelView) {
self.parent = parent
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if self.parent.viewIsShowing {
webView.evaluateJavaScript("clickReady()", completionHandler: nil)
}
}
}

private func loadInitialContent(in webView: WKWebView) {
let embedHTML = """

body {
margin: 0;
background-color: black;
}
.iframe-container iframe {
top: 0;
left: 0;
width: 100%;
height: 100%;
}





var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
var isPlaying = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: '\(link)',
playerVars: { 'playsinline': 1, 'controls': 0},
events: {
'onStateChange': function(event) {
if (event.data === YT.PlayerState.ENDED) {
player.seekTo(0);
player.playVideo();
}
}
}
});
}

function clickReady() {
player.playVideo();
}

function watchPlayingState() {
if (isPlaying) {
player.playVideo();
} else {
player.pauseVideo();
}
}


"""

webView.scrollView.isScrollEnabled = false
webView.loadHTMLString(embedHTML, baseURL: nil)
}
}

func widthOrHeight(width: Bool) -> CGFloat {
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first

if width {
return window?.screen.bounds.width ?? 0
} else {
return window?.screen.bounds.height ?? 0
}
}


Источник: https://stackoverflow.com/questions/770 ... ideo-to-pl
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»