0

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.

1 Answers1

1

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 initing a URL object. Additionally, checking the scheme is super easy because URL has a property scheme that we can check against the required parameters.

thecoolwinter
  • 861
  • 7
  • 22
  • Wonderful - Your answer is a combination of the two best answer's i've received from similar but improperly posed posts I made earlier. Thanks a lot @thecoolwinter! – Adam Dahan Aug 23 '21 at 02:14
  • @AdamDahan Totally :) glad I could help! – thecoolwinter Aug 23 '21 at 02:15
  • @AdamDahan much easier just check if the URL is not a file URL [isFileURL](https://developer.apple.com/documentation/foundation/nsurl/1408782-isfileurl) – Leo Dabus Aug 23 '21 at 02:15
  • @AdamDahan I already told you how you should approach this. Make a url request if it is not a file url and check the response – Leo Dabus Aug 23 '21 at 02:20