将 UIWebView 限制为特定 URL (Swift) [英] Limit UIWebView to specific URL (Swift)

查看:52
本文介绍了将 UIWebView 限制为特定 URL (Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Swift 中开发一个具有 UIWebView 的 iOS 应用程序,但是我需要它只适用于一个域,并且在该 UIWebView 中单击的任何外部链接都可以在 Safari 中打开.(例如,指向 http://example.com 的所有链接将在 UIWebView 中打开,但指向 http://twitter.com 的链接将在 Safari 中打开).

I'm trying to develop an iOS app that features a UIWebView in Swift, however I need it to only work with one domain, and any external links clicked on in that UIWebView to be opened in Safari. (E.G. All links to http://example.com will open within the UIWebView, but a link to http://twitter.com would open in Safari).

我在网上找到了几个解决方案,但只有一个 Swift 版本(在这里找到:UIWebView openSafari 中的链接) 可以打开 Safari 中的每个链接,我只希望外部链接这样做.

I have found a couple of solutions online but the only Swift version (found here: UIWebView open links in Safari) works to open every link in Safari, I just want external ones to do so.

有人可以帮忙吗?谢谢.

Could anyone help? Thanks.

推荐答案

我在 Swift 方面的表现一定比我想象的要好...

I must be getting better at Swift than I thought...

修改我最初找到的解决方案(在问题中链接),我想出了这个替代方案,允许通过我的 URL,但在 Safari 中打开任何外部 URL.

Modifying the solution that I found originally (linked in the question), I came up with this alternative that allows through my URL, but opens any external URLs in Safari.

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

不要忘记将此代码从 UIWebView 委托给视图控制器,它应该可以正常工作(只要您将 example.com 替换为您的 URL.

Don't forget to delegate this code from the UIWebView to the View Controller, and it should work fine (just as long as you replace example.com with your URL.

请投票支持这条评论,因为我花了一整天时间搜索教程和论坛,并认为我的最终解决方案是一个非常干净的解决方案!

Please vote up this comment, as I have spent all day searching through tutorials and forums, and think that my final solution is a pretty clean one!

这篇关于将 UIWebView 限制为特定 URL (Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆