Good afternoon guys.
In Java we have a function called shouldOverrideUrlLoading that checks all URLs 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?
Good afternoon guys.
In Java we have a function called shouldOverrideUrlLoading that checks all URLs 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?
You need to make your View Controller conform to 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 shouldStartLoadWithRequest method inside the webview view 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'
}
Do not forget to define that your view controller is the webview delegate, just add webView.delegate = self in the viewDidLoad method:
webView.delegate = self
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
}
}