How to use an imgLoad before loading WebView

1

In swift I can load a webView by doing the following:

1 - Add UIWebView to my View.

2 - I create an Outlet called webView in my viewcontroller.swift

3 - I enter the following code in my function viewDidLoad

 let url = NSURL (string: "http://pt.stackoverflow.com");
 let requestObj = NSURLRequest(URL: url!);
 myWebView.loadRequest(requestObj);

It turns out that in this loadRequest I'm already calling my webView and it works, however I do not know how I can add a loading image to not leave that screen blank.

    
asked by anonymous 27.11.2015 / 18:13

1 answer

2

Implement the UIWebView delegate to receive its status changes. When you start uploading the webview you put something on the screen (image, activity indicator, HUD). When it finishes loading, either successfully or with error, you remove it.

For example, to display an image while the webview loads:

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var myWebView: UIWebView!
    var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL (string: "https://pt.stackoverflow.com")
        let requestObj = NSURLRequest(URL: url!)
        myWebView.loadRequest(requestObj)
        myWebView.delegate = self
        addLoaderImage()
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        removeLoaderImage()
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        removeLoaderImage()
    }

    func addLoaderImage() {
        imageView = UIImageView(frame: myWebView.frame)
        imageView.image = UIImage(named: "loadingWebView.png")
        self.view.addSubview(imageView)
    }

    func removeLoaderImage() {
        imageView.removeFromSuperview()
        imageView = nil
    }
}
    
27.11.2015 / 19:42