Search code examples
swiftwebviewuiwebviewuiwebviewdelegate

Trying to get webView to load 2 URLS after another


Im trying to make it load 2 webviews after one gets finished loading then it will go to the next one and start to load that one and if both of them are loaded it will send a notification.

It gives an error after

        @IBAction func MybuttonAction(_ sender: Any) {

    if !googleLoaded {

        googleLoaded = true
        let url = URL(string: "https://google.com")
        let requestObj = URLRequest(url: url!)
        webView.loadRequest(requestObj)
        print("Google loaded")
        let url1 = URL(string: "https://yahoo.com")
        let requestObj1 = URLRequest(url: url1!)
        webView.loadRequest(requestObj1)
        print("yahoo loaded")

    } else if !yahooLoaded {

        yahooLoaded = true

        let alertController = UIAlertController(title: "ThankYou", message: "Both Views have finished loading", preferredStyle: .alert)

        let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        alertController.addAction(defaultAction)

        self.present(alertController, animated: true, completion: nil)
        self.aviLoadingSpinner.stopAnimating()
    }
}


func webViewDidFinishLoad(_ webView: UIWebView) {

}

Solution

  • You must use UIWebViewDelegate webViewDidFinishLoad. That method is called when a request is completed.

    import WebKit
    
    class yourViewController: UIViewController, UIWebViewDelegate {
    
     @IBoutlet weak var webView: UIWebView!
    
     var googleLoaded: Bool = false 
     var yahooLoaded: Bool = false 
    
     override func viewDidLoad() {
         self.webView.delegate = self
     }         
    
     func webViewDidFinishLoad(_ webView: UIWebView) {
    
         if !googleLoaded { 
    
             googleLoaded = true
             let url = URL(string: "https://yahoo.com")
             let requestObj = URLRequest(url: url!)
             webView.loadRequest(requestObj) 
    
         } else if !yahooLoaded { 
    
             yahooLoaded = true
             let alertController = UIAlertController(title: "ThankYou", message: "Both Views have finished loading", preferredStyle: .alert)
    
             let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
             alertController.addAction(defaultAction)
    
             self.present(alertController, animated: true, completion: nil)
             self.aviLoadingSpinner.stopAnimating() 
         }
     }
    
     @IBAction func MybuttonAction(_ sender: Any) {
    
         let url = URL(string: "https://google.com")
         let requestObj = URLRequest(url: url!)
         webView.loadRequest(requestObj)
    }