Reputation: 5
I am trying to write some code that lets me both validate that a string is in fact a valid web address to reach a remote server && be able to unwrap it safely into a url for usage.
From what gathered from various posts and Apple's source code:
URLComponents is a structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.
and based on w3 schools:
A URL is a valid URL if at least one of the following conditions holds:
The URL is a valid URI reference [RFC3986]....
Would this code suffice to detect addresses that reach remote servers on the world wide web?
import Foundation
extension String {
/// Returns `nil` if a valid web address cannot be initialized from self
var url: URL? {
guard
let urlComponents = URLComponents(string: self),
let scheme = urlComponents.scheme,
isWebServerUrl(scheme: scheme),
let url = urlComponents.url
else {
return nil
}
return url
}
/// A web address normally starts with http:// or https:// (regular http protocol or secure http protocol).
private func isWebServerUrl(scheme: String) -> Bool {
(scheme == WebSchemes.http.rawValue || scheme == WebSchemes.https.rawValue)
}
}
Can you provide some feedback on this approach and let me know if there are any optimizations that can be made? or if it's incorrect?
Any and all comments are appreciated.
Upvotes: 0
Views: 205
Reputation: 1002
You could go even simpler and do
import Foundation
extension String {
/// Returns `nil` if a valid web address cannot be initialized from self
var url: URL? {
return URL(string: self)
}
/// A web address normally starts with http:// or https:// (regular http protocol or secure http protocol).
var isWebURL: Bool {
get {
guard let url = self.url else { return false }
return url.scheme == "http" || url.scheme == "https"
}
}
}
Explanation
Initializing a URL
using a string will return nil
if the string isn't a valid url, so you can get the url by just init
ing a URL object. Additionally, checking the scheme is super easy because URL
has a property scheme
that we can check against the required parameters.
Upvotes: 1