How to check url?

I am trying to verify the url using NSURL but it does not 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 Escolas cannot return the truth, what am I doing wrong?

+4
source share
2 answers

I think you are missing a URL with UIApplication.sharedApplication().canOpenURL(url), for example, change the code to this:

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 NSURLdoes not check the URL, do you think, according to Apple :

This method expects that it URLStringwill only contain characters that are allowed in a well-formed URL. All other characters must be properly escaped. Any skipped percent characters are interpreted using UTF-8 encoding

, .

+6

[Swift 3.0]

, String .

extension String {

    func isValidURL() -> Bool {

        if let url = URL(string: self) {

            return UIApplication.shared.canOpenURL(url)
        }

    return false 
    }
}
0

Source: https://habr.com/ru/post/1626262/


All Articles