Check URL loaded in a Webview

Asked

Viewed 383 times

2

Good afternoon, everyone.

In Java we have a function called shouldOverrideUrlLoading that checks every URL loaded inside a Webview, so I can create conditions to decide how the APP should behave. Does anyone know how to do this through Swift?

  • How come every url ? you want to load the url and then do some action ? or when it is being loaded ? I don’t get it right

  • Webview will load a URL. After the View is loaded the user will start browsing inside the webview as if he were on a website. I need to run a method that checks every time a new url is loaded inside the webview, to define the behavior of the app according to the user’s actions.

  • you have tried using the webViewDidFinishLoad method?

  • already. but still not exactly what I need..

1 answer

1


You need to make your View Controller fit the Uiwebviewdelegate protocol

First add Uiwebviewdelegate to the view controller that contains your uiwebview

class ViewController: UIViewController, UIWebViewDelegate {

Connect your webview to your view controller

@IBOutlet weak var webView: UIWebView!

Add the method shouldStartLoadWithRequest within the webview controller:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    print("shouldStartLoadWithRequest")
    if let newURL = request.URL {
       print(newURL.absoluteString)
    }
    return true   // para que a nova url seja carregada retorne `true` ou se voce quiser bloquear retorne `false`
}

Don’t forget to define that your view controller is the delegate of webview, just add webView.delegate = self in the viewDidLoad method:

webView.delegate = self

demo project

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        guard let googleURL = NSURL(string: "https://www.google.com/") else { return }
        webView.loadRequest( NSURLRequest(URL: googleURL) )
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let newURL = request.URL {
           print(newURL.absoluteString)
        }
        return true
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.