thatidiotguy
thatidiotguy

Reputation: 8991

What is the iOS proper URL encoding of "+" character?

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.

[email protected]

to

me%2Bblah%[email protected]?

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.

Upvotes: 2

Views: 297

Answers (2)

Aaron Brager
Aaron Brager

Reputation: 66242

let email = "[email protected]"

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

Upvotes: 1

rob mayoff
rob mayoff

Reputation: 385600

println(("[email protected]" as NSString)
    .stringByAddingPercentEncodingWithAllowedCharacters(
        NSCharacterSet.alphanumericCharacterSet()))

Output:

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

In Objective-C:

NSString *encodedString =
    ["[email protected]" stringByAddingPercentEncodingWithAllowedCharacters:
        [NSCharacterSet alphanumericCharacterSet]];

Upvotes: 0

Related Questions