Home > Software design >  parsing string to URL always returning a valid url on swift
parsing string to URL always returning a valid url on swift

Time:09-21

I dont know why this code is always returning a valid url (test) instead of returning nil

 if let url2 = URL(string: "test") {
   print(url2)
}

Anyone knows why this happen?

CodePudding user response:

fixed it by:

 if let url2 = URL(string: "test"), (url.scheme == "http" || url.scheme == "https")   {
   print(url2)
}

CodePudding user response:

What you are doing is not checking whether url is valid or not. Your code is just preparing url which will be created using any text.

To check the URL is valid or not, use below function.

// Swift 5
func verifyUrl (urlString: String?) -> Bool {
    if let urlString = urlString {
        if let url = NSURL(string: urlString) {
            return UIApplication.shared.canOpenURL(url as URL)
        }
    }
    return false
}
  • Related