2016-12-06 1 views
0

pages in Youtube을 열기 위해 WKWebView을 사용하고 있습니다. 문제는 개봉시 동영상 재생이 시작되고 전체 화면으로 이동하기 때문에 원하는 동작이 아닌 것입니다. 동영상은 삽입되지 않으며 설명, 설명 등이 포함 된 전체 페이지입니다.ios - WkWebView에서 Youtube 자동 재생 사용 안 함

재생을 중지 할 수있는 방법이 있습니까?

+0

나는 동일한 문제가 있습니다. –

답변

0

작동합니다. 의견을 읽으십시오.

import UIKit 
import WebKit 
import RxSwift 

class WebViewController: UIViewController { 

    let webview: WKWebView 

    init() { 
     // add config 
     let config = WKWebViewConfiguration() 
     config.allowsInlineMediaPlayback = true 
     if #available(iOS 10.0, *) { 
      config.mediaTypesRequiringUserActionForPlayback = .video 
     } 
     self.webview = WKWebView(frame: .zero, configuration: config) 

     super.init(nibName: nil, bundle: nil) 
     webview.frame = view.bounds 
     subscribeURL() 
    } 

    private func subscribeURL() { 
     self.webview.rx.url 
     .shareReplay(1) 
      .subscribe(onNext: { [weak self] url in 
       guard let url = url else { return } 
       // Navigation Delegate can not detect transition because YouTube is Single Page Application. 
       startInlinePlayApplyInterval() 
      }) 
      .addDisposableTo(disposeBag) 
    } 

    private func startInlinePlayApplyInterval() { 
     // There is time rag to come out new video element so start repeat interval. 
     //Useful Timer extension: http://stackoverflow.com/a/39600244/3276863 
     let loop = Timer.schedule(repeatInterval: 0.2) { [weak self] timer in 
      self?.applyInlinePlay { success in 
       if success { 
        timer?.invalidate() 
       } 
      } 
     } 
     Timer.schedule(delay: 2) { _ in 
      loop?.invalidate() 
     } 
    } 

    private func applyInlinePlay(completion: @escaping (Bool)->Void) { 
     // add attributes 'webkit-playsinline','playsinline','controls' to video element 
     let script = "(function(){var applied=document.querySelector('video').attributes.playsinline!=undefined;if(applied){return false}var videos=document.querySelectorAll('video');var attrList=['webkit-playsinline','playsinline','controls'];for(video of videos){for(attr of attrList){video.setAttribute(attr,'');}}return true})();" 
     webview.evaluateJavaScript(script) { res, err in 
      let isSuccessToApply: Bool = (res as? Bool) ?? false 
      completion(isSuccessToApply) 
     } 
    } 
} 
관련 문제