Reputation: 692
In my Project I need to save a user given url. So I need to check if it's a valid URL and most importantly if it will be open in a WKWebView
. My Problem: I can verify an url but can't make sure it will be open or not?
Here is my code :
func canOpenURL(_ string: String?) -> Bool {
guard let urlStr = string,
let url = URL(string: urlStr)
else { return false }
if !UIApplication.shared.canOpenURL(url) { return false }
let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[regEx])
return predicate.evaluate(with: urlStr)
}
I used something like this:
if canOpenURL(ckeckedURL) {
print("URL Can Open")
} else {
print("Url cant Open")
}
The Problem is:
When I give ckeckedURL = https://klsklaksalskalksalksalkslkas.com
it also shows me valid. I know it's a valid url but it will not open in WKWebView. Is there any way to check it?
Upvotes: 0
Views: 599
Reputation: 1713
If I understand correctly, you want to know if the user entered an url to a 'responding' website..? If that's the case you can make a URLRequest and check if the statusCode is successful, like this:
guard let url = URL(string: "https://asdasdasd.com") else { fatalError() }
URLSession.shared.dataTask(with: url) { data, resp, err in
guard let resp = resp as? HTTPURLResponse else { print("not a HTTP URL"); return }
if (200..<300).contains(resp.statusCode){
print("valid")
}else{
print("invalid")
}
}.resume()
Keep in mind that the dataTask completion will run asynchronously, so you probably want to have a waiting / loading system while you check the url...
Upvotes: 1