karlml karlml - 3 months ago 13x
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


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.