2

Is there seriously not a way natively to URL Encode the value of a query string parameter that has a "+" character in it?

e.g.

me+blah@domain.net

to

me%2Bblah%40@domain.net?

I tried solutions like posted in these other questions, but those do not properly encode that email.

Swift - encode URL

How do I URL encode a string

A swift solution would be preferred as that is what I am working in at the moment, but I am capable of translating Objective-C Code to swift code for the most part.

Specifically I am trying to x-www-form-urlencoded encode query string values in the body of POST request.

Community
  • 1
  • 1
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
  • 2
    Specify how the string/URL currently *is* being encoded (including at what steps such is applied) as context is very important to when `+` should, shouldn't, and might be percent encoded. The "proper encoding" is defined by these rules, outside (and long before) iOS. – user2864740 Oct 01 '14 at 19:59
  • @user2864740 I'm not sure I understand, I gave an example of input, and desired output. Currently the "+" character does not get encoded with any of the solutions provided on the other stackoverflow questions. – thatidiotguy Oct 01 '14 at 20:07

2 Answers2

1
let email = "me+blah@domain.net"

let output = CFURLCreateStringByAddingPercentEscapes(nil, email as NSString, nil, ":/?@!$&'()*+,;=" as NSString, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))

// output = "me%2Bblah%40domain.net"

CFURLCreateStringByAddingPercentEscapes doesn't escape + or @ by default, but you can specify it (as I did along with other characters, in the ":/?@!$&'()*+,;=" string).


Edit: If you want output to be a Swift string:

let output = (CFURLCreateStringByAddingPercentEscapes(nil, email as NSString, nil, ":/?@!$&'()*+,;=" as NSString, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as NSString) as String
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
0
println(("me+blah@domain.net" as NSString)
    .stringByAddingPercentEncodingWithAllowedCharacters(
        NSCharacterSet.alphanumericCharacterSet()))

Output:

Optional("me%2Bblah%40domain%2Enet")

In Objective-C:

NSString *encodedString =
    ["me+blah@domain.net" stringByAddingPercentEncodingWithAllowedCharacters:
        [NSCharacterSet alphanumericCharacterSet]];
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • But periods should not be encoded when the content type is `x-www-form-urlencoded` – thatidiotguy Oct 01 '14 at 20:21
  • You can add more characters to the character set, but is it really worth it? The periods will be decoded properly. You are **allowed** to encode more characters than you are **required** to encode. – rob mayoff Oct 01 '14 at 20:22