Alessandro Zago
Alessandro Zago

Reputation: 803

Swift onfinish load event of a UIWebView

I'm loading a pdf in WebView from my server with this code :

    webView = UIWebView(frame: CGRectMake(0, y, screenSize.width, screenSize.height-y))    
    let url : NSURL! = NSURL(string: urlFile)        
    webView?.loadRequest(NSURLRequest(URL: url))        
    webView?.opaque = false;
    webView?.backgroundColor = UIColor.clearColor()                
    webView?.scalesPageToFit = true;    
    self.view.addSubview(webView!)

This code works but how can i receive an event "onPageLoad"? sorry for bad english, i'm italian(:

Upvotes: 5

Views: 17818

Answers (4)

nickinade
nickinade

Reputation: 106

In case someone is looking solution for WKWebView, implement WKNavigationDelegate:

add webView.navigationDelegate = self

and then use:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

}
    

Upvotes: 6

SwiftDeveloper
SwiftDeveloper

Reputation: 7368

Just use effective with ;

 func webViewDidFinishLoad(webView : UIWebView) {

 // Here your loaded codes.

 }

Upvotes: 0

pkc
pkc

Reputation: 8516

After webView?.loadRequest(NSURLRequest(URL: url)) this, set the webView to self (Write the below line).

webView.delegate = self

Implement the webview delegate methods.

You will get callback in func webViewDidFinishLoad(_ webView: UIWebView) on completing the page load.

   func webViewDidFinishLoad(webView: UIWebView) {
        //handle the callback here when page load completes
    }

Upvotes: 2

Nirav D
Nirav D

Reputation: 72440

You need to implement UIWebViewDelegate like this and use webViewDidFinishLoad to know the page is loaded successfully, for that set the webView delegate with your viewController like this, and implement the webViewDidFinishLoad method inside your viewController like below example.

import UIKit
class ViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = UIWebView(frame: CGRectMake(0, y, screenSize.width, screenSize.height-y))
        let url : NSURL! = NSURL(string: urlFile)
        webView?.loadRequest(NSURLRequest(URL: url))
        webView?.opaque = false;
        webView?.backgroundColor = UIColor.clearColor()
        webView?.scalesPageToFit = true; 
        webView?.delegate = self// Add this line to set the delegate of webView
        self.view.addSubview(webView!)       
    }

    func webViewDidFinishLoad(webView : UIWebView) {
        //Page is loaded do what you want
    }
}

Upvotes: 16

Related Questions