如何在UIWebView中更改src值?

时间:2017-10-20 12:13:02

标签: ios uiwebview

在UIWebview中我想要更改

<iframe src=“//player.vimeo.com/video/164231311?autoplay=1” width=“700" height=“394” frameborder=“0" webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe>

<iframe src=“//player.vimeo.com/video/164231311" width=“700” height=“394" frameborder=“0” webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe>

因为我希望向用户显示播放按钮而不是暂停按钮,因为iOS上不允许自动播放。用户可以直接看到播放按钮而不是暂停按钮,如下图所示。

我该如何以简单的方式做到这一点?我尝试了一些像

这样的东西
webView.stringByEvaluatingJavaScript(from:“document.getElementsByTagName(…) 
到目前为止没有成功。

enter image description here

1 个答案:

答案 0 :(得分:1)

在这里,我制作了粗略的演示代码来解决您的问题。用你的逻辑,它将解决你的问题。 经过测试,看起来效果很好。

import UIKit

class ViewController: UIViewController,UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        webView.loadRequest(URLRequest(url: URL(string: "file:///Users/user/Downloads/index.html")!))
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        // get your current iframe src value
        let iframeSrcValue:String = webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('iframe')[0].src")!

        // Here is your current value with AutoPlay
        print(iframeSrcValue)

        //Create new URL without Auto Play
        let modifiedSrcValue = "https://www.youtube.com/embed/td8pYyuCIIs"

        // Apply it to webview
        let evaluate: String = "document.getElementsByTagName('iframe')[0].src='\(modifiedSrcValue)';"
        webView.stringByEvaluatingJavaScript(from: evaluate)
    }

}