URL(string:)生成失败问题

257 阅读1分钟

例如:

let url = URL(string: "http://en.wikipedia.org/wiki?params={\"category\":\"jump\"}")

在iOS17之后的系统上正常,但是iOS17之前的系统上会返回nil。

原因: 字符串 URL 参数之间存在空格。需要使用addingPercentEncoding对字符串进行编码。 如下:

let url = URL(string: urlStr?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")

参考: 当我们打开 URL 的初始化方法的官方文档 developer.apple.com/documentati…

For apps linked on or after iOS 17 and aligned OS versions, URL parsing has updated from the obsolete RFC 1738/1808 parsing to the same RFC 3986 parsing as URLComponents. This unifies the parsing behaviors of the URL and URLComponents APIs. Now, URL automatically percent- and IDNA-encodes invalid characters to help create a valid URL.

翻译一下就是 URL 解析已从过时的 RFC 1738/1808 解析更新为与 URLComponents 相同的 RFC 3986 解析。

参考链接: juejin.cn/post/732447…
stackoverflow.com/questions/4…