假设我有以下网址:https://something.com/room/order/12345555/product/543333?is_correct=true
。这是一种Deeplink,我应该解析其参数并显示一些ViewController。我对值为12345555、543333和true感兴趣。实际上,很容易获得这些参数。
为了获得12345555或543333,我们可以使用pathComponents
返回的URL ["/", "room", "order", "12345555", "product", "543333"]
。要获取查询项(is_correct:true),我们可以使用URLComponents。一切都清晰而简单。
但是假设我的链接包含#
为path https://something.com/room/#/order/12345555/product/543333?is_correct=true
。现在,对于此链接,pathComponents
返回时将["/", "room"]
忽略其他所有内容。当然,查询参数也存在问题。
为什么#
符号会如此影响?我该如何解决问题?我应该替换#
为某个东西还是URL
从Swift包含一些辅助方法?谢谢。
您遇到的问题是这#
不是路径的一部分,而是引入了存储在中的URL的新组件url.fragment
。这类似于您是否拥有https://example.com/foo/?test=/bar
。?test=
不是路径组件,而是查询的开始。
您可以采用两种方法。
如果https://something.com/room/order/12345555/product/543333?is_correct=true
和https://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。
您采用哪种方法以及进行多少消毒取决于您的用例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句