I am using NSMutableURLRequest. While sending the parameters to server I have to encode it so I am encoding it using dataUsingEncoding(NSUTF8StringEncoding) Swift 2.3 but it is removing + sign from the string. Is there any alternate way of doing it?

Sample Code:

let URL = NSURL(string: urlString)
let urlRequest = NSMutableURLRequest(URL: URL!)
urlRequest.HTTPMethod = "POST"

urlRequest.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")

urlRequest.HTTPBody = Parameters.dataUsingEncoding(NSUTF8StringEncoding); 
1

There are 1 answers

0
Smile On

The plus (+) sign is a standard shortcut for a space, you have to replace the + with the %2d before encoding. Please have a look at this Doc for other signs

let URL = NSURL(string: urlString)
let urlRequest = NSMutableURLRequest(URL: URL!)
urlRequest.HTTPMethod = "POST"

urlRequest.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
Parameters = Parameters.stringByReplacingOccurrencesOfString("+", withString: "%2b")
urlRequest.HTTPBody = Parameters.dataUsingEncoding(NSUTF8StringEncoding); 

You can also url encode it if it is not helping you out Like

Parameters = Parameters.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

and then replace the (+) sign with %2d and than encode it using dataUsingEncoding Hope it helps