Prevent user from leaving website in Swift

753 views Asked by At

I want to create a WebView in an iPad-App, that displays a website. I want to prevent the user to click on links that link to other websites (e.g. Facebook, Twitter, ...) but he should be allowed to move around on the current website freely.

How can I achieve this?

I tried with:

func webView(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    let newWebsite:String = (request.URL?.path)!
    print(newWebsite)
    if newWebsite.rangeOfString("float-schwabing") != nil{
        return true;
    } else {
        return false;
    }
}

It didn't work though. I can still access other websites.

It would be awesome, if somebody could help me with this.

2

There are 2 answers

4
Huy Tran On

The problem should be in your if statement, did you try to return false in all case yet? just to see if it worked or not?

func webView(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    return false
}

And... it's rare but why not, did you add delegate to your webView?

0
Rashwan L On

As you have done you should be able to navigate within your website, you might have some internal links. Try the below code instead of how you have done it today:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if String(request.URL!).rangeOfString("YOUR WEBSITE") != nil{
        return true
    }
    else{
        return false
    }
}

You basically check if the request url contains your websites name, if it does you might want to open that link otherwise you donĀ“t.