我想使用 URL Scheme 从我的应用程序打开苹果地图。
let url = URL(string: "http://maps.apple.com/?q=대한민국")
使用此 URL 进行测试,但它始终为零。
这是我的猜测。
有没有人知道这个或如何解决这个问题?
此处各种答案中的编码都是正确的,但您通常不应在整个 URL 上使用
.addingPercentEncoding
。正如参数 urlQueryAllowed
所指出的,该编码仅适用于查询部分,不适用于其他部分,如路径、主机或权限。
对于硬编码的 URL,您可以对其进行手动编码,但如果您以编程方式构建 URL,则应使用 URLComponents:
var components = URLComponents(string: "http://maps.apple.com/")!
components.queryItems = [
URLQueryItem(name: "q", value: "대한민국")
]
// Or, if more convenient:
// components.query = "q=대한민국"
let url = components.url!
这确保了每个片段都被正确编码,并且在以编程方式构建 URL 时避免了混乱的字符串插值。
作为
addingPercentEncoding
出错的示例,考虑一个 IDN 域,例如 Bücher.example:
let urlString = "https://Bücher.example/?q=대한민국"
print(urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))
// https://B%C3%BCcher.example/?q=%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD
这不正确。 IDN 域必须使用 Punycode 编码,而不是百分比编码。
var components = URLComponents(string: "http://Bücher.example/")!
components.query = "q=대한민국"
print(components.url!)
// http://xn--bcher-kva.example/?q=%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD
你必须对你的路径进行编码,因为它包含 URL 中不允许的字符:
let urlString = "http://maps.apple.com/?q=대한민국"
let encodedUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: encodedUrlString!)
print(url)
输出:
http://maps.apple.com/?q=%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD
URL 最初仅定义为 ASCII。
当你尝试将包含非ascii 字符的字符串转换为URL 时,由于上述原因,它不能这样做。您需要以某种方式使用 %xx(UTF-8 的十六进制值)格式对其进行编码。
由于非 ascii 字符在查询字符串中,您可以使用以下代码在 Swift 中执行此操作:
urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)