3

I obtained the following code from here to open all other links that do not match my domain in Safari:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == UIWebViewNavigationType.LinkClicked {
        UIApplication.sharedApplication().openURL(request.URL!)
        return false
    }
    return true
}

Although how can I allow another specified domain to be opened within my UIWebView instead of Safari, such as paypal.com?

Community
  • 1
  • 1
Fizzix
  • 23,679
  • 38
  • 110
  • 176

1 Answers1

3

You can store a list of allowed URLs and filter on the host name of the request URL. If the host matches one of the allowed URLs then return true to allow the URL to load in the web view. Otherwise use UIApplication.openURL() to open the URL in Safari.

For example:

let safeList = [ "paypal.com", "google.com" ]

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    if navigationType == UIWebViewNavigationType.LinkClicked {

        if let host = request.URL?.host where safeList.contains(host) {
            return true // Open in web view
        }

        UIApplication.sharedApplication().openURL(request.URL!)
        return false
    }

    return true
}
Luke Van In
  • 5,215
  • 2
  • 24
  • 45