【问题标题】:Display alert 6 seconds after WKWebView loadsWKWebView 加载后 6 秒显示警报
【发布时间】:2020-09-09 19:33:10
【问题描述】:

我有这个但不确定如何设置一个 6 秒的计时器,例如在 WKWebView 加载之后。我有这个代表didFinish navigation。我认为这行不通:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    showAlert()
}

func showAlert() {
    let alert = UIAlertController(title: "Loaded ", message: "In webview currently", preferredStyle: UIAlertController.Style.alert)
    self.present(alert, animated: true, completion: nil)
}

【问题讨论】:

标签: ios swift wkwebview


【解决方案1】:

您可以为此使用DispatchQueue asyncAfter。它在分配给它的最后期限之后执行操作。以下是您的解决方案。

func showAlert() {
    let alert = UIAlertController(title: "Loaded ", message: "In webview currently", preferredStyle: .alert)
    DispatchQueue.main.asyncAfter(deadline: .now()+6.0) {
        self.present(alert, animated: true, completion: nil)
    }
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         Timer.scheduledTimer(timeInterval: 6, target: self, selector: #selector(showAlert), userInfo: nil, repeats: false)
    }
    
    @objc func showAlert() {
        let alert = UIAlertController(title: "Loaded ", message: "In webview currently", preferredStyle: UIAlertController.Style.alert)
        self.present(alert, animated: true, completion: nil)
    }
    

    【讨论】:

    • 此类任务应避免使用计时器。更好地使用DispatchQueue asyncAfter。此外,一旦任务完成,您应该使计时器无效,否则它将继续运行。
    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2021-01-18
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多