ホーム 技術ネタ

wkwebviewで音声の再生を許可する - iPad + Swift3.0

環境

  • html5
  • html
  • HTML5
  • HTML
  • Javascript
  • js
  • audio
  • wkwebview
  • webview
  • iPad
  • Swift3.0
  • swift
  • SWIFT

やりたいこと

wkwebviewに描画したウェブアプリケーションの中でユーザーアクションに応じてhtml5 + Javascriptで実装した音声ファイルを再生させたい。普通に実装しても音声は再生されなかった。下記のようにapp側でちょっと工夫しないといけなかった。

実装

 

let url = "url入れて"

    lazy var wkwebView: WKWebView = {


        //WKWebViewのConfigurationを定義
        let config = WKWebViewConfiguration()
        //iPadで音声の再生を許可する
        config.requiresUserActionForMediaPlayback = false
        //configuration: configで設定を読み込む
        var webView = WKWebView(frame: self.view.bounds , configuration: config)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.isUserInteractionEnabled = true

        return webView
    }()

 

ソース

 

import UIKit
import WebKit

class ViewController: UIViewController,WKNavigationDelegate,WKUIDelegate {

    let url = "url入れて"

    lazy var wkwebView: WKWebView = {


        //WKWebViewのConfigurationを定義
        let config = WKWebViewConfiguration()
        //iPadで音声の再生を許可する
        config.requiresUserActionForMediaPlayback = false
        //configuration: configで設定を読み込む
        var webView = WKWebView(frame: self.view.bounds , configuration: config)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.isUserInteractionEnabled = true

        return webView
    }()

    lazy var progBar: UIProgressView = {

        var pro = UIProgressView(frame: CGRect(x: 0, y: 44, width: self.view.frame.width, height: 1))
        pro.progress = 0.0
        pro.progressTintColor = UIColor.green
        pro.trackTintColor = UIColor.gray
        return pro
    }()

    //ステータスバーを隠す
    override var prefersStatusBarHidden: Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()


        self.view.addSubview(self.wkwebView)
        self.navigationController?.navigationBar.addSubview(self.progBar)
        self.wkwebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        let request = NSURLRequest(url: URL(string:url)!)
        self.wkwebView.load(request as URLRequest)

    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            progBar.setProgress(Float(self.wkwebView.estimatedProgress), animated: true)

            if(self.wkwebView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0
                })
            }
        }

    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.wkwebView.title
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("\(#function)")
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {

    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {

    }

    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {

    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("失败")
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {

        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            self.wkwebView.load(navigationAction.request)
        }
        return nil
    }

    func webViewDidClose(_ webView: WKWebView) {

    }

    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {

    }

    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {

    }
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {

    }


    override func viewWillDisappear(_ animated: Bool) {
        self.wkwebView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
}

 

参考

gitHub

iOSアプリ内のUIWebViewでHTML5オーディオを自動再生する。

iOS10: Auto play not working on WKWebView (requiresUserActionForMediaPlayback = false)

Pocket
LinkedIn にシェア



新規webサービスの開発の依頼ならoffテク⭐️

低コストで、Reactなどモダン言語での新規webサービス開発を承ります

-ホーム, 技術ネタ
-, , ,

Copyright© off , 2020 All Rights Reserved Powered by AFFINGER5.