In many native iOS applications, webviews are used to perform certain tasks. Once the initial urls is set to webview, it becomes difficult to intercept redirection url(if any), which is handled by webview. But sometimes we need to intercept these urls to perform specific actions.

Most common example is while making payments through apps. Many redirections happen while doing such payments. After the redirection, we need to return to the app. To detect status of payment, we need to detect certain url or domain and prevent webview to load further.

To perform such task, iOS has provided UIWebViewDelegate protocol, the methods of which can be used to detect loading request.


With use of UIWebViewDelegate protocol, it becomes really easy to intercept such redirections by webview. We just need to adopt UIWebViewDelegate protocol in our UIViewController.

class WebViewController: UIViewController, UIWebViewDelegate {

To detect which url is currently being loaded, below are UIWebViewDelegate methods.

  • Before url starts loading
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    let currentLoadingUrl: String = (request.mainDocumentURL?.absoluteString)!
    return true

With this webview delegate method we can detect which url is going to load and can prevent loading by just return false such as in above method add following check

if currentLoadingUrl.containsString("<domain to check>"){
    return false

With this we can block certain domain or url in webview or perform the required action.

  • After url has been loaded
func webViewDidFinishLoad(webView: UIWebView) {

We can perform required action after the particulat url has been loaded.

Thus, in above mentioned example of payments through app, we can detect final redirection url of app website and return to app by simply closing webview by self.dismissViewControllerAnimated(true, completion: nil).

Note: We can’t detect the url in webViewDidStartLoad method of UIWebViewDelegate as the request property of the webview isn’t assigned until the request has been loaded.