如何将 Activity 指标添加到 WKWebView (Swift 3)

How to add Activity Indicator to WKWebView (Swift 3)

我的应用程序中有一个 wkwebview,我想向其添加一个 activity 指示器。我希望它在 webview 加载时出现在它出现的位置,并在加载完成时消失,它消失。你能给我一些代码来做到这一点吗?这是我的代码:

@IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!


@IBOutlet var containerView: UIView? = nil


override func viewDidLoad() {
    super.viewDidLoad()

    guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }

    webView = WKWebView(frame: self.view.frame)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.isUserInteractionEnabled = true
    webView.navigationDelegate = self

    self.view.addSubview(self.webView)

    let request = URLRequest(url: url)
    webView.load(request)

}


func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    // Check if a link was clicked
    if navigationAction.navigationType == .linkActivated {

        // Verify the url
        guard let url = navigationAction.request.url else { return }
        let shared = UIApplication.shared

        // Check if opening in Safari is allowd
        if shared.canOpenURL(url) {

            // Ask the user if they would like to open link in Safari
            let alert = UIAlertController(title: "Do you want to open Safari?", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) -> Void in
                // User wants to open in Safari
                shared.open(url, options: [:], completionHandler: nil)
            }))
            alert.addAction(UIAlertAction(title: "Opps, no.", style: .cancel, handler: nil))

            present(alert, animated: true, completion: nil)

        }
        decisionHandler(.cancel)
    }
    decisionHandler(.allow)
}

func webViewDidStartLoad(_ : WKWebView) {
    Activity.startAnimating()
}

func webViewDidFinishLoad(_ : WKWebView) {
    Activity.startAnimating()
}

我正在使用 xcode 8 和 swift 3

创建一个 IOS 应用

viewDidLoad 中,您需要将 activityIndicator 添加为 subView,就像您为 webView 所做的那样。由于它是一个插座,请确保 activityIndicator 位于您的 webView 之上,这样您就可以开始使用了。您还想在 webView 停止 加载时将 activity.hidden 设置为 true

小写 'Activity' 插座也是一个很好的经验法则。

override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.Activity)

guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }

webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self

self.view.addSubview(self.webView)


let request = URLRequest(url: url)
webView.load(request)

您还在webViewDidFinishLoad()中调用了activity.startAnimating。确保在 webView 完成加载时调用 activity.stopAnimating()。编码愉快!

    func webViewDidFinishLoad(_ : WKWebView) {
    Activity.stopAnimating()
    Activity.hidden = true
}

拜托,下面的代码工作正常。

@IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!
@IBOutlet var containerView: UIView? = nil

override func viewDidLoad() {
    super.viewDidLoad()
    
    guard let url = URL(string: "http://www.facebook.com") else { return }
    webView = WKWebView(frame: self.view.frame)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.isUserInteractionEnabled = true
    self.view.addSubview(self.webView)
    let request = URLRequest(url: url)
    webView.load(request)
    
    // add activity
    self.webView.addSubview(self.Activity)
    self.Activity.startAnimating()
    self.webView.navigationDelegate = self
    self.Activity.hidesWhenStopped = true
    
}

实现下面这两个委托方法:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    Activity.stopAnimating()
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    Activity.stopAnimating()
}

如果它不起作用,请告诉我。

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

    var webView: WKWebView!
    var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        webView = WKWebView(frame: CGRect.zero)
        webView.navigationDelegate = self
        webView.uiDelegate = self

        view.addSubview(webView)

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray

        view.addSubview(activityIndicator)

        webView.load(URLRequest(url: URL(string: "http://google.com")!))
    }

    func showActivityIndicator(show: Bool) {
        if show {
            activityIndicator.startAnimating()
        } else {
            activityIndicator.stopAnimating()
        }
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        showActivityIndicator(show: false)
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        showActivityIndicator(show: true)
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        showActivityIndicator(show: false)
    }
}

Swift 5 版本

这个概念很简单,可以移植到早期的 swift 版本。

这是一个 class 我们可以将其用作父 class 任何我们想要 webview 的地方。

import UIKit
import WebKit

class CustomWebViewController: UIViewController, WKNavigationDelegate {
    var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.style = .gray
        activityIndicator.isHidden = true

        view.addSubview(activityIndicator)
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndicator.isHidden = false
        activityIndicator.startAnimating()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicator.stopAnimating()
        activityIndicator.isHidden = true
    }
}

如果我们有一个带有 webview 的 UIViewController,我们可以从 CustomWebViewController 继承,它会为我们处理剩下的事情。记得连接webview IBOutlet.

import UIKit
import WebKit

class FirstViewController: CustomWebViewController {

    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.navigationDelegate = self

        let url = URL(string: "https://google.com")
        webView.load(URLRequest(url: url!))
    }
}
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
    webView = WKWebView(frame: CGRect.zero)
    webView.navigationDelegate = self;
    webView.uiDelegate = self


    activityIndicator = UIActivityIndicatorView()
    activityIndicator.hidesWhenStopped = true
    activityIndicator.center = self.view.center
    activityIndicator.style = UIActivityIndicatorView.Style.large

    webView.addSubview(activityIndicator)
    view = webView

    let load_url = URL(string: "https://google.com/")!
    webView.load(URLRequest(url: load_url))
    activityIndicator.startAnimating()

    let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
    toolbarItems = [refresh]
    navigationController?.isToolbarHidden = false
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
    activityIndicator.stopAnimating()
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    activityIndicator.startAnimating()
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    activityIndicator.stopAnimating()
}
}

请尝试下面的代码,它对我来说工作正常,如果有任何问题,请告诉我提前谢谢。

import UIKit
import WebKit

class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

@IBOutlet weak var contentView: UIView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()

    setupView()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.setupWebView()
    self.loadData()
}

fileprivate func setupView() {

    self.contentView.isHidden = true
    self.activityIndicatorView.startAnimating()
}

fileprivate func setupWebView() {

    let webConfiguration = WKWebViewConfiguration()

    webView = WKWebView(frame: contentView.bounds, configuration: webConfiguration)
    webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.contentView.addSubview(webView)
    self.webView.allowsBackForwardNavigationGestures = true
    webView.uiDelegate = self
    webView.navigationDelegate = self
}

fileprivate func loadData() {

    if let url = URL(string: "http://google.com") {

        /// For loading PDF content 
        if contentType == .pdf {

              if let data = try? Data(contentsOf: url) {
                   self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: url)
              }
        } else {

           let request = URLRequest(url: url)
           webView.load(request)
        }  
   }
}

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

    activityIndicatorView.stopAnimating()
    self.contentView.isHidden = false
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    activityIndicatorView.stopAnimating()
}
}