如何在Swift中用#解析URL?

How to parse URL with # in Swift?

假设,我有以下 URL:https://something.com/room/order/12345555/product/543333?is_correct=true。它有点深link,我应该解析它的参数并显示一些ViewController。我对 12345555、543333 和 true 等值感兴趣。其实这些参数很容易得到

为了得到 12345555 或 543333,我们可以使用 pathComponents of URL which returns ["/", "room", "order", "12345555", "product", "543333"]。要获取查询项 (is_correct: true),我们可以使用 URLComponents。一切都简单明了。

但是假设我的 link 包含 # 作为路径 https://something.com/room/#/order/12345555/product/543333?is_correct=true。现在,对于这个 link,pathComponents returns 只是 ["/", "room"] 忽略其他一切。当然查询参数也有问题

为什么#符号影响如此?我该如何解决问题?我应该用某些东西替换 # 还是 Swift 中的 URL 包含一些辅助方法?谢谢。

您 运行 遇到的问题是 # 不是路径的一部分,而是引入了存储在 url.fragment 中的 URL 的新组件.这类似于您有 https://example.com/foo/?test=/bar?test= 不是路径组件,而是查询的开头。

您有两种方法可以采用。

如果 https://something.com/room/order/12345555/product/543333?is_correct=truehttps://something.com/room/#/order/12345555/product/543333?is_correct=true 可以互换使用,因为在浏览器中查看任一页面都会让您进入同一页面,您可以在您的过程中进行清理:

var rawUrl = ...
var sanitizedUrl = url.replacingOccurrences(of: "/#/", with: "/")
var url = URL(string: url)

您执行多少消毒取决于您的应用程序。可能你只想做 (of: "/room/#/", with: "/room/")

另一种选择,如果您知道您的片段总是看起来像部分片段 URL,则将片段传递到 URL:

let url = URL(string: rawUrl)!
let fragmentUrl = URL(string: url.fragment!, relativeTo: url)!

let fullPathComponents = url.pathComponents + fragmentUrl.pathComponents[1...];
var query = fragmentUrl.query

上述方法产生:["/", "room", "order", "12345555", "product", "543333"] 加入 URL。

您采用哪种方法以及进行多少消毒取决于您的用例。