I am wondering what code I should use to check if a url is valid. AND I DON'T MEAN CHECKING FOR KEY WORDS LIKE "https//" or ".com" I mean checking if the url can be opened (aka is it a valid url). Truthfully I can not find an answer anywhere for this so anything would be a step in the right direction.
Asked
Active
Viewed 3,071 times
1
-
It frustrates me when people don't read my question even though I put something in all caps. Let me say it again though, I know how to check if a url contains certain keywords but in that stack overflow post it only states how to do that. If you were to type in google.c with that code it would count as a valid url. However if you open that link it takes you to a invalid url page. – coder12345 Dec 09 '20 at 21:23
-
3Instead of pushing back, try to learn. If a URL is valid as a URL string, _it is valid._ If you mean something else, don't call it "valid". What happens when you try to _go_ there on the network is a contingent fact. A URL can be valid without being _reachable._ It might not be reachable because the network is down. Or it might not exist, but if the domain exists and you get a 404, that _is_ reachable (it is not an error of any kind). You need to put some more thought into what it is you want to know. – matt Dec 09 '20 at 21:34
-
1Thank you for your insight I will keep that in mind. – coder12345 Dec 09 '20 at 21:36
-
3Someone who might be new to coding won't know the difference between valid and reachable... While I do think there's room for growth on OP's side, how about we get in the habit of, when marking something as dup, we leave a comment as to why... It's very clear by OP's post that they did look for themselves and didn't find the other post useful - that points to not a lack of effort but a lack of knowledge. Don't downvote/mark as dup without giving reason else you're part of the problem. – Byron Coetsee Jul 20 '21 at 11:59
1 Answers
4
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
}
}

Leo Dabus
- 229,809
- 59
- 489
- 571
-
Do HTTP servers have a default implementation for the HEAD method? I was not aware it existed until now, and in the few servers I've implemented, I did not provide a HEAD implementation. I bet I'm not alone. – Duncan C Dec 09 '20 at 21:32
-
This does not not work although it requires the https:// for it to be a valid url. In other words google.com would be invalid however https://google.com would be valid. – coder12345 Dec 09 '20 at 21:35
-
@DuncanC I was just trying to avoid downloading the URL content. Of course you can simply skip the HEAD part. – Leo Dabus Dec 09 '20 at 21:41
-
@coder12345 it does not require `https`. this will depend on your app transport security settings. BTW `google.com` even though it works on Safari it is invalid. It doesn't have an URL scheme. – Leo Dabus Dec 09 '20 at 21:43
-
@LeoDabus sorry to be all annoying about this but what is app transport security settings and how could I change it so google.com is valid. – coder12345 Dec 09 '20 at 21:47
-
`google.com` will never be valid. You need to provide a scheme. I will post a link about app transport security – Leo Dabus Dec 09 '20 at 21:53
-
[App Transport security](https://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http) – Leo Dabus Dec 09 '20 at 21:54
-
@LeoDabus that shows how to add specific urls, I am looking for how to add and url/domain that is reachable. – coder12345 Dec 09 '20 at 22:11
-
No you can add a specific domain or allow arbitrary loads. Any https URL should work without setting the app transport security settings – Leo Dabus Dec 09 '20 at 22:27
-
What do you mean add specific domain and when I set allows arbitrary loads to true google.com is still not reachable – coder12345 Dec 09 '20 at 22:36
-
@coder12345 not sure why do you think google.com should be accessible. You need to provide a scheme "http" or "https" – Leo Dabus Dec 09 '20 at 23:06
-
You shouldn't set allows arbitrary loads to true. Why would you need to allow your app to load any URL? Are you trying to create a web browser? – Leo Dabus Dec 09 '20 at 23:08
-
I am creating a social media app where users can post things. When they go to write something I want to detect if there is any urls and if there is than I want that to become a link. – coder12345 Dec 10 '20 at 01:01
-
I don't think you should restrain a link to be posted if it is not reachable at the moment the user posts it. – Leo Dabus Dec 10 '20 at 01:06
-
1This is a great answer because using WKWebView if the url isn't reachable, it will show just a blank white screen. The user won't understand what's the problem. This provides a good way to show something to indicate that the url isn't reachable. – Lance Samaria Dec 13 '21 at 12:47