【发布时间】:2021-08-23 01:59:03
【问题描述】:
我正在尝试编写一些代码,让我既可以验证字符串实际上是到达远程服务器的有效网址,又可以安全地将其解包到 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)
}
}
您能否就这种方法提供一些反馈,并让我知道是否可以进行任何优化?或者如果它不正确?
感谢所有 cmets。
【问题讨论】:
-
您对有效网址的定义是什么?根据您的定义,以下网址是否有效? apple.coom
-
远程服务器的网址。我重新措辞了这个问题:thumbs_up:
标签: ios swift urlcomponents