Url Validation in Swift

How to check validity of URL in Swift?

If your goal is to verify if your application can open a URL, here is what you can do. Although safari can open the URL, the website might not exist or it might be down.

// 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
}

As a side note, this does not check whether or not a URL is valid or complete. For example, a call that passes "https://" returns true.

How to check if a url is valid in Swift?

You can create an URLRequest, set its httpMethod to "HEAD", send an asynchronous request and check if the HTTPURLResponse statusCode is equal to 200:

extension URL {
func isReachable(completion: @escaping (Bool) -> ()) {
var request = URLRequest(url: self)
request.httpMethod = "HEAD"
URLSession.shared.dataTask(with: request) { _, response, _ in
completion((response as? HTTPURLResponse)?.statusCode == 200)
}.resume()
}
}


let url1 = URL(string: "https://stackoverflow.com/questions/65224939/how-to-check-if-a-url-is-valid-in-swift")!
url1.isReachable { success in
if success {
print("url1 is reachable") // url1 is reachable
} else {
print("url1 is unreachable")
}
}


let url2 = URL(string: "https://stackoverflow.com/question/index.html")!
url2.isReachable { success in
if success {
print("url2 is reachable")
} else {
print("url2 is unreachable") // url2 is unreachable
}
}

How do I validate an URL?

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.

Validate URL in Swift 3

func validateUrl (urlString: NSString) -> Bool {
let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluateWithObject(urlString)
}

This worked.

Validate URL without scheme

It's not possible to add a valid scheme to URL because no one knows which prefix will be add to which URL. You can just validate a URL with the help of regex.

I searched and modified the regex.

extension String { 
func isValidUrl() -> Bool {
let regex = "((http|https|ftp)://)?((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: self)
}
}

I tested it with below urls:

print("http://stackoverflow.com".isValidUrl()) 
print("stackoverflow.com".isValidUrl())
print("ftp://127.0.0.1".isValidUrl())
print("www.google.com".isValidUrl())
print("127.0.0.1".isValidUrl())
print("127".isValidUrl())
print("hello".isValidUrl())

Output

true 
true
true
true
true
false
false

Note: 100% regex is not possible to validate the email and url

Regex for validating URL with brackets in Swift

You can add (?:\(\d+\))? before $:

"^(http|https|ftp)://([a-zA-Z0-9.-]+(?::[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])|localhost|([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+\\.(com|ru|kz|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(?::[0-9]+)*(/($|[a-zA-Z0-9.,?'\\\\+&%$#=~_-]+))*(?:\\(\\d+\\))?$"

The (?:\(\d+\))? matches an optional occurrence of a sequence of (, one or more digits, ).

Note:

  • {1} is always redundant in regex, remove these
  • You do not need to escape a lot of chars that are special inside square brackets, like ., ;, $, etc. Only [, ], ^, -, ] and \ are special inside square brackets
  • - at the end of the character class (the [...] thing) does not have to be escaped
  • I replaced some capturing groups with non-capturing as you are not extracting part of the match.

Check if URL is valid in Swift 4

You're probably crashing because you're using the ! operator and not checking that it will work. Instead try:

@IBAction func startBrowser(_ sender: Any) {
if let urlString = self.urlTextField.text {
let url: URL?
if urlString.hasPrefix("http://") {
url = URL(string: urlString)
} else {
url = URL(string: "http://" + urlString)
}
if let url = url {
let sfViewController = SFSafariViewController(url: url)
self.present(sfViewController, animated: true, completion: nil)
print ("Now browsing in SFSafariViewController")
}
}
}

This should give you the idea of how to handle the different cases, but you probably want something more sophisticated which can deal with https and strips whitespace.

How to validate an url on the iPhone

Thanks to this post, you can avoid using RegexKit.
Here is my solution (works for iphone development with iOS > 3.0) :

- (BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx =
@"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}

If you want to check in Swift my solution given below:

 func isValidUrl(url: String) -> Bool {
let urlRegEx = "^(https?://)?(www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\.[a-z]{2,6}(/[-\\w@\\+\\.~#\\?&/=%]*)?$"
let urlTest = NSPredicate(format:"SELF MATCHES %@", urlRegEx)
let result = urlTest.evaluate(with: url)
return result
}


Related Topics



Leave a reply



Submit