我使用的是NSURLComponents,但我似乎无法获得正确编码的查询值。我需要最终的网址表示为%2B的+。
let baseUrl = NSURL(string: "http://www.example.com")
let components = NSURLComponents(URL: baseUrl, resolvingAgainstBaseURL: true)
components.queryItems = [ NSURLQueryItem(name: "name", value: "abc+def") ]
XCTAssertEqual(components!.string!, "http://www.example.com?connectionToken=abc%2Bdef")失败!
输出等于:
http://www.example.com?connectionToken=abc+def 不
http://www.example.com?connectionToken=abc%2Bdef我尝试了几个变体,但似乎根本不能将其输出为%2B。
发布于 2017-06-23 20:18:42
正如其他答案所提到的,默认情况下"+“不是在iOS上编码的。但如果您的服务器需要对其进行编码,以下是如何进行编码的方法:
var comps = URLComponents(url: self, resolvingAgainstBaseURL: true)
// a local var is needed to fix a swift warning about "overlapping accesses" caused by writing to the same property that's being read.
var compsCopy = comps
compsCopy?.queryItems = [URLQueryItem(name: "name", value: "abc+def")]
comps?.percentEncodedQuery = compsCopy?.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")https://stackoverflow.com/questions/31577188
复制相似问题