web-dev-qa-db-ja.com

WKWebView(Swift 3)にアクティビティインジケーターを追加する方法

アプリにwkwebviewがあり、アクティビティインジケーターを追加したいと思います。 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とIOS 3を使用してSwiftアプリを作成しています

9
iFunnyVlogger

正常に動作しているコードの下でください。

@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
    webView.navigationDelegate = self
    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

}

以下の2つのデリゲートメソッドを実装します。

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

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

機能していない場合はお知らせください。

27
Sandy
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)
    }
}
13
Ian Pinto

viewDidLoadでは、activityIndicatorの場合と同じように、subViewwebViewとして追加する必要があります。アウトレットなので、activityIndicatorwebViewの上にあることを確認してください。また、truestopsロード時に_activity.hidden_をwebViewに設定することもできます。

また、「アクティビティ」アウトレットを小文字にするのも良い経験則です。

_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
}
_
2
Alex Blair

Swift 5バージョン

コンセプトは、以前のバージョンに移植できるほど単純ですSwiftバージョン。

これは、Webビューが必要な任意の場所で親クラスとして使用するクラスです。

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!))
    }
}
2
yeyo

以下のコードを試してみてください。問題がないかどうか事前にお知らせください。

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()
}
}
0
Elamurugan
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()
}
}
0