如果我创建这样的网址:
guard var urlComponents = URLComponents(url: "https://example.com/something", resolvingAgainstBaseURL: false) else {
return
}
let queryItems = URLQueryItem(name: "token", value: token)
urlComponents.queryItems = [queryItems]
guard let urlWithQueryItem = urlComponents.url else {
return
}
我希望最终结果类似于https://example.com/something#token=7as78f6asd678768asd768asd678
而不是默认的https://example.com/something?token=7as78f6asd678768asd768asd678
(我正在寻找比搜索和替换?字符更聪明的东西)
由于
答案 0 :(得分:2)
正如其他人所说,URLQueryItem对象更适用于查询字符串与锚点/片段。话虽如此,下面是一个功能,可以帮助您完成您的问题。
func constructURL(withURL urlBase: String, andFragmentFromQueryItem queryItem: URLQueryItem) -> URL?{
guard let url = URL(string:urlBase) else {
return nil
}
guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
let fragmentKey = queryItem.name
let fragmentValue = queryItem.value ?? ""
urlComponents.fragment = "\(fragmentKey)=\(fragmentValue)"
guard let urlWithFragment = urlComponents.url else {
return nil
}
return urlWithFragment
}
let url = constructURL(withURL:"https://example.com/something",
andFragmentFromQueryItem: URLQueryItem(name: "token", value: "tokenValue"))
let urlString = url?.absoluteString
print("\(urlString!)")
这是一个代码的工作Swift小提琴的链接。 http://play.swiftengine.io/code/8JKI3/2
答案 1 :(得分:0)
但是,您可以使用URLComponents
向URL添加片段。只需使用fragment
属性:
urlComponents.fragment = "token=\(token)"