2017-10-21 27 views
1

我做了這個webview,我想顯示一個錯誤消息,當沒有互聯網連接或失去互聯網連接,而使用該應用程序。Swift:如何在沒有互聯網連接的情況下在webview中顯示錯誤消息?

這是我的代碼:

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

} 

回答

1

您可以使用委託方法:

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) 
} 
+0

但如何向用戶顯示一條警告消息? –

+0

對不起:)你可以使用UIAlertController!我編輯了答案。 –

+0

它的工作!謝謝! :D –

相關問題