0

I have a uiactivity view in my project. I want to start animating while the page is loading and stop and hide when the webview finally loads. this is not working in my case.

I have tried to use the UIWebViewDelegate, but it is deprecated.

class WebviewViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    let disposeBag = DisposeBag()
    var specURL:String?

    override func viewDidLoad() {
        super.viewDidLoad()
        configureUIActivityView()
        _ = loadWebview()
            .subscribe(onSuccess: { url in
                DispatchQueue.main.async {
                    self.webView.loadRequest(URLRequest(url: url))
                    self.activityIndicator.stopAnimating()
                    self.activityIndicator.isHidden = true
                }
            })
    }

    func loadWebview() -> Single<URL> {
        return Single<URL>.create { single in
            guard let url = URL(string: self.specURL!.trimmingCharacters(in: .whitespacesAndNewlines)) else {
                assertionFailure("no view available")
                //single(.error(NetworkError.noImage))
                return Disposables.create {}
            }
            single(.success(url))
            return Disposables.create {}
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

It is better to use the WKWebView for achieving since as you mentioned that the UIWebViewDelegate is deprecated.

Here is a simple example for monitoring the loading status of the WKWebView using KVO.

import WebKit

class ViewController: UIViewController, WKUIDelegate {

    private var webView: WKWebView!

    override func loadView() {
         let webConfiguration = WKWebViewConfiguration()
         webView = WKWebView(frame: .zero, configuration: webConfiguration)
         webView.uiDelegate = self
         view = webView
         webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
     }

     override func viewDidLoad() {
         super.viewDidLoad()
         let myURL = URL(string: "http://www.apple.com")
         let myRequest = URLRequest(url: myURL!)
         webView.load(myRequest)
     }

     override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
         guard let keyPath = keyPath, let change = change else { return }
         switch keyPath {
         case "loading":
             if let loading = change[.newKey] as? Bool {
                 print("Is webview loading: \(loading)")
             }
         default:
             break
         }
     }

     deinit {
        webView.removeObserver(self, forKeyPath: "loading")
     }
 }
axel
  • 422
  • 2
  • 14