Reputation: 16246
Background:
I have read several questions answers here, but the more I read, it only gets more confusing.
Task:
I need to send a POST URL request with "trailing" parameters in the URI, like this:
http://www.myhostname.com/functionName?parameter1=value1¶meter2=value2
Typically, I will create the parameter string with a format and insert the values for each parameter, like this:
let value1 = "Hello"
let value2 = "World"
let parameterString = "?parameter1=\(value1)¶meter2=\(value2)"
let requestURL = baseURL.URLByAppendingPathComponent("\(fucntionName)\(parameterString)")
Questions:
URLQueryAllowedCharacterSet
, or do I need to define a custom character set?Update:
If I escape using NSCharacterSet.URLQueryAllowedCharacterSet()
and print()
the resulting string, the ?
, =
and &
remain intact. If I use that string to instantiate an NSURL
and then print its path
property (that is, a String
), I get the same output.
But if I pass said NSURL
instance as-is to print()
, the ? alone gets percent-escaped (into %3F
).
Upvotes: 0
Views: 236
Reputation: 9923
To create your String contain the URL first by combine Base URL with the param first and encode it using stringByAddingPercentEncodingWithAllowedCharacters
then only turns it to URL, the "? & = . /" should not be percent escaped in the URL
let escapedSearchText = searchText.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
let urlString = String(format:"%@/%@?parameter1=%@¶meter2=%@",hostName, functionName,value1, value2)
//http://www.myhostname.com/functionName?parameter1=value1¶meter2=value2
let url = NSURL(string: urlString)
return url!
Upvotes: 1