You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

URL的host属性已废弃,替代方法在特定场景下崩溃

解决方案:URL新Host方法崩溃问题处理

URL的host属性在iOS 16.1和macOS 13中已被废弃,替代方法host(percentEncoded:)在处理不符合RFC 1808标准的URL(如lorem.com)时会崩溃,而旧方法仅返回nil。以下是可行的解决方案:

方案1:补全URL Scheme后调用新方法

无scheme的URL会被视为相对路径,是触发崩溃的核心原因。通过补全scheme后再获取host:

extension URL {
    func safeHost(percentEncoded: Bool = false) -> String? {
        if scheme != nil || isFileURL {
            return try? host(percentEncoded: percentEncoded)
        }
        guard let absoluteURL = URL(string: "http://\(absoluteString)") else {
            return nil
        }
        return try? absoluteURL.host(percentEncoded: percentEncoded)
    }
}

// 调用示例
let url = URL(string: "lorem.com")
print(url?.safeHost()) // 输出 "lorem.com"

方案2:利用URLComponents解析Host

URLComponents对非标准URL的兼容性更强,可避免崩溃:

extension URL {
    func safeHostViaComponents() -> String? {
        var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
        if components?.scheme == nil {
            guard let absoluteURL = URL(string: "http://\(absoluteString)") else {
                return nil
            }
            components = URLComponents(url: absoluteURL, resolvingAgainstBaseURL: false)
        }
        return components?.host
    }
}

// 调用示例
let url = URL(string: "lorem.com")
print(url?.safeHostViaComponents()) // 输出 "lorem.com"

方案3:手动字符串解析(兜底)

针对极端场景,可直接从URL字符串中提取host:

func extractHost(from urlString: String) -> String? {
    let trimmed = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
    let noScheme = trimmed.replacingOccurrences(of: "^[a-zA-Z]+://", with: "", options: .regularExpression)
    if let end = noScheme.rangeOfCharacter(from: CharacterSet(charactersIn: "/?#"))?.lowerBound {
        return String(noScheme[..<end])
    }
    return noScheme.isEmpty ? nil : noScheme
}

// 调用示例
print(extractHost(from: "lorem.com")) // 输出 "lorem.com"
print(extractHost(from: "lorem.com/path?query=test")) // 输出 "lorem.com"

内容的提问来源于stack exchange,提问作者Vicente Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:40:33