Prevent user from leaving website in Swift

妖精的绣舞 提交于 2019-12-11 23:33:10

问题


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.


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/36435941/prevent-user-from-leaving-website-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!