简体   繁体   中英

iOS Swift Webview show image while loading

I'm loading a Web-View in my iOS App.

Is it possible to show an image while the Webview is loading in the background?

I found something for Objective-C but nothing for Swift 2.2.

How can I detect if the Web-View finished loading?

Edit:

   func webViewDidStartLoad(webView: UIWebView!) {
    loadingView.viewWithTag(1)?.hidden = false 
    print("Webview started Loading")
    }

func webViewDidFinishLoad(webView: UIWebView!) {
loadingView.viewWithTag(1)?.hidden = true 
print("Webview did finish load")
}

from: How to show image while page is loading in swift?

Conform to the UIWebViewDelegate protocol and set your view controller as the web view's delegate. The function webViewDidFinishLoad(_ webView: UIWebView) will be called when it has finished loading. You can set your image over the web view in the beginning then clear it in this function.

Edit:

I can't place it over the web view can I?

Yes, do exactly that. If you set the image to hidden it won't affect the user's interaction with the web view.

So finally its working...

Here my Solution for Swift 2.2

class YourViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {

    super.viewDidLoad()

    // For the Loading image: Create an ImageView programmatically and add id to the view
        let imageName = "YourPicture.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)
        imageView.tag = 1;
        imageView.frame = CGRect(x: 50, y: 250, width: 300, height: 100)
        view.addSubview(imageView)


      let url = "http://apple.com"

        let requestURL = NSURL(string:url)
        let request = NSURLRequest(URL: requestURL!)
        webView.delegate = self
        webView.loadRequest(request)        

    }

    func webViewDidFinishLoad(webView: UIWebView) {

       // UIWebView object has fully loaded.
      if(webView.stringByEvaluatingJavaScriptFromString("document.readyState") == "complete") {

        // Manually add a delay, showing the Webview takes some time..
        // For Swift 2.2
        let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 2 * Int64(NSEC_PER_SEC))

        dispatch_after(time, dispatch_get_main_queue()) {
        //put your code which should be executed with a delay here

           self.view.viewWithTag(1)?.hidden = true}
        }

        print("Webview did finish load")
    }

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM