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

为何Swift中使用指定URL Scheme创建URL实例时返回nil?

问题原因

URL(string:)构造方法要求传入的字符串必须严格符合URL规范,包含未编码的非ASCII字符(比如你这里的中文“犬”)会直接返回nil,这就是你构造失败的核心原因。Safari能正常跳转是因为浏览器会自动对地址栏的非ASCII字符做百分号编码处理,底层实际使用的是编码后的合规URL。

解决方案

方法1:手动对参数做百分号编码

// 对中文参数进行URL编码
guard let encodedWord = "犬".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
    // 编码失败兜底逻辑
    return
}
let midoriURL = URL(string: "kotoba://dictionary?word=\(encodedWord)")!

方法2:使用URLComponents构造(更推荐)

无需手动处理编码逻辑,容错性更高:

var components = URLComponents()
components.scheme = "kotoba"
components.host = "dictionary"
components.queryItems = [URLQueryItem(name: "word", value: "犬")]

guard let midoriURL = components.url else {
    // URL生成失败兜底逻辑
    return
}

注意事项

URL构造成功后如果跳转失败,需要检查项目Info.plist中是否已经将kotoba添加到LSApplicationQueriesSchemes数组中,iOS系统对跨应用跳转的Scheme有白名单校验,未加入白名单的Scheme无法正常跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:36:07