I'm trying to validate a url using NSURL but it doesn't work for me.
func verifyUrl (urlString: String?) -> Bool {
if let urlString = urlString {
if let _ = NSURL(string: urlString) {
return true
}
}
return false
}
let ex1 = "http://google.com"
let ex2 = "http://stackoverflow.com"
let ex3 = "Escolas" // Not a valid url, I think
verifyUrl(ex1) // true
verifyUrl(ex2) // true
verifyUrl(ex3) // true
I think that "Escolas" can't return true, what am I doing wrong?
I think what you're missing is open the url with UIApplication.sharedApplication().canOpenURL(url)
for example, change your code to this one:
func verifyUrl (urlString: String?) -> Bool {
if let urlString = urlString {
if let url = NSURL(string: urlString) {
return UIApplication.sharedApplication().canOpenURL(url)
}
}
return false
}
verifyUrl("escola") // false
verifyUrl("http://wwww.google.com") // true
The constructor of NSURL
not validate the url as you think, according to Apple:
This method expects
URLString
to contain only characters that are allowed in a properly formed URL. All other characters must be properly percent escaped. Any percent-escaped characters are interpreted using UTF-8 encoding
I hope this help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With