Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Couldn't encode Plus character in URL + swift

I am using a GET method in which i have to pass a email address in the URL. API expects it to be encoded. I tried with the encoding options but the '+' character couldnt be encoded.

I tried with the following code

let encodedEmail = emailAddressTxt.text!.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)

let urlString = "http://www.example.com/User/GetUserDetailsByEmailAddress?EmailAddress=\(encodedEmail!)"

print(escapedString)

It prints http://www.example.com/User/GetUserDetailsByEmailAddress?EmailAddress=mano+1%40gmail.com

Where the '@' character is only encoded and '+' is not encoded.

like image 975
Mano Avatar asked Jan 10 '17 05:01

Mano


2 Answers

Unfortunately, both CharacterSet.urlHostAllowed and CharacterSet.urlQueryAllowed contains + as allowed. And for historical reason, most web servers treat + as a replacement of whitespace (), so you need to escape +.

For such purpose, you may need to define your own CharacterSet:

extension CharacterSet {
    static let rfc3986Unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
}

let emailAddressText = "[email protected]"

let encodedEmail = emailAddressText.addingPercentEncoding(withAllowedCharacters:.rfc3986Unreserved)

print(encodedEmail!) //->mano%2B1%40gmail.com
like image 118
OOPer Avatar answered Oct 20 '22 01:10

OOPer


When you use .urlHostAllowed character set '+' is not encoded.

Add extension to String like below

public func stringByAddingPercentEncodingToData() -> String? {
    let finalString = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)?.replacingOccurrences(of: "&", with: "%26").replacingOccurrences(of: "+", with: "%2B")
    return finalString
}

You can do something like this.

like image 4
Baji Bhosale Avatar answered Oct 20 '22 02:10

Baji Bhosale