karlml karlml - 1 year ago 80
Swift Question

How to only allow certain URLs in app

Is there a way to allow an app to load only certain URLs? I was thinking there was something like Exception Domains in App Transport Security settings, except this is not about allowing arbitrary loads from certain URL, but rather to allow only certain URLs and block all others, whether or not HTTPS/HTTP. Thanks

Answer Source

You can use something like this in your AppDelegate:

optional func application(_ app: UIApplication,
              openURL url: NSURL,
              options options: [String : AnyObject]) -> Bool
    //Return true or false depending on if you want 
    //this application to open the URL.

In the comments you mention that you are using this all in a single UIWebView. In that case you can do the following:

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

    return handleRequest(URL)

@available(iOS 8.0, *)
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    let request = navigationAction.request;
    let url = request.URL


That bit of code handles both UIWebView and WKWebView.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download