如何在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
}