检测有效网址

Detecting a valid web address

我正在尝试编写一些代码,让我都可以验证一个字符串实际上是一个 到达远程服务器的有效网址 && 能够安全地将它解包到url 用法。

从各种帖子和 Apple 的源代码中收集的内容:

URLComponents is a structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.

并基于 w3 所学校:

A URL is a valid URL if at least one of the following conditions holds:

The URL is a valid URI reference [RFC3986]....

此代码是否足以检测 到达万维网上远程服务器的地址?

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

您能否就此方法提供一些反馈,让我知道是否可以进行任何优化?或者它是否不正确?

感谢任何和所有评论。

你可以更简单地做

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

说明 如果字符串不是有效的 url,使用字符串初始化 URL 将 return nil,因此您可以通过 [=13] 获得 url =]ing 一个 URL 对象。此外,检查方案非常简单,因为 URL 有一个 属性 scheme,我们可以根据所需的参数进行检查。