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

查看:918
本文介绍了如何在Swift中检查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?

推荐答案

如果您的目标是验证您的应用程序是否可以打开网址这是你能做的。虽然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.

func verifyUrl (urlString: String?) -> Bool {
    //Check for nil 
    if let urlString = urlString { 
        // create NSURL instance
        if let url = NSURL(string: urlString) {
            // check if your application can open the NSURL instance 
            return UIApplication.sharedApplication().canOpenURL(url)
        }
    }
    return false
}

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

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