2017-10-21 52 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 –

相关问题