每隔(N)秒刷新WebView

时间:2018-01-25 04:13:29

标签: ios swift uiwebview

我正在搜索代码,我可以每N秒刷新一次webView。我得到的答案很少,但由于我在iOS开发方面很新,我无法确定在哪里放置刷新代码段。

这是我的代码:

import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WKWebView!
    var websites = "www.example.com/start/home.asp"



    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self as? WKNavigationDelegate
        view = webView


    }


    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://" + websites)!
        webView.load(URLRequest(url: url) as URLRequest)
        webView.allowsBackForwardNavigationGestures = true

    }


    //MARK:- WKNavigationDelegate

    func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
        print(error.localizedDescription)
    }
    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Strat to load")
    }
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        print("finish to load")
    }

}

以下是我要添加的代码段:

[NSTimer scheduledTimerWithTimeInterval:5 target:selfselector:@selector(updateWeb) userInfo:nil repeats:YES];

-(void)updateWeb
{
    [webView reload];
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用NSTimer每5秒调用一次该方法,并使用UIWebview的-reload方法。

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://" + websites)!
    webView.load(URLRequest(url: url) as URLRequest)
    webView.allowsBackForwardNavigationGestures = true

    Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}


@objc func update() {
     webView.reload()
}