Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate an URL?

Tags:

swift

I'm trying to validate a url using NSURL but it doesn't work for me.

Example:

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?

like image 861
Gabriel Rodrigues Avatar asked Jan 27 '16 22:01

Gabriel Rodrigues


1 Answers

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.

like image 150
Victor Sigler Avatar answered Oct 31 '22 11:10

Victor Sigler