如何在 Swift 中检查 URL 的有效性? [英] How to check validity of URL in Swift?

查看:49
本文介绍了如何在 Swift 中检查 URL 的有效性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试让应用程序启动 URL 的默认浏览器,但前提是输入的 URL 有效,否则会显示一条消息,指出该 URL 无效.

Trying to make an app launch the default browser to a URL, but only if the URL entered is valid, otherwise it displays a message saying the URL is invalid.

我将如何使用 Swift 检查有效性?

How would I go about checking the validity using Swift?

推荐答案

如果您的目标是验证您的应用程序是否可以打开 URL,您可以执行以下操作.尽管 safari 可以打开 URL,但该网站可能不存在或已关闭.

If your goal is to verify if your application can open a URL, here is what you can do. Although safari can open the URL, the website might not exist or it might be down.

// Swift 5
func verifyUrl (urlString: String?) -> Bool {
    if let urlString = urlString {
        if let url = NSURL(string: urlString) {
            return UIApplication.shared.canOpenURL(url as URL)
        }
    }
    return false
}

作为旁注,这检查 URL 是否有效或完整.例如,一个通过https://"的调用返回真.

As a side note, this does not check whether or not a URL is valid or complete. For example, a call that passes "https://" returns true.

这篇关于如何在 Swift 中检查 URL 的有效性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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