Gabriel Rodrigues
Gabriel Rodrigues

Reputation: 510

How do I validate an URL?

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?

Upvotes: 5

Views: 11246

Answers (2)

Edouard Barbier
Edouard Barbier

Reputation: 1845

[Swift 3.0]

Very similar but I used an extension on String to achieve the same result.

extension String {

    func isValidURL() -> Bool {

        if let url = URL(string: self) {

            return UIApplication.shared.canOpenURL(url)
        }

    return false 
    }
}

Upvotes: 0

Victor Sigler
Victor Sigler

Reputation: 23451

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.

Upvotes: 9

Related Questions