1

I made this webview and I want to show an error message when there is no internet connection or losing internet connection, while using the app.

This is my code:

import UIKit


class FirstViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView1: UIWebView!

    var refreshControl:UIRefreshControl?

    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView1.delegate = self


        let url = URL(string: "https://pharmacyuni.blogspot.com")
        webView1.loadRequest(URLRequest(url: url!))
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func goBack(_ sender: Any) {
        webView1.goBack()
    }


    func webViewDidStartLoad(_ webView: UIWebView)
    {
        activityIndicator.startAnimating()
    }
    func webViewDidFinishLoad(_ webView: UIWebView)
    {
        activityIndicator.stopAnimating()
    }


    @IBAction func refreshButton(_ sender: Any) {
        webView1.reload()
    }

}
Pinkie Swirl
  • 2,375
  • 1
  • 20
  • 25

1 Answers1

2

You can use the delegate method:

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    print("webview did fail load with error: \(error)")

    let message: String = error.localizedDescription

    let alert = UIAlertController(title: "something", message: message, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in
    // use action here
    })
    self.present(alert, animated: true)
}
Ramprasath Selvam
  • 3,868
  • 3
  • 25
  • 41
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24