iosswiftafnetworking

UTF8 Encoding in iOS / swift for email containing +


How to encode URL parameters with UTF8 encoding in Query string format URL/param1/param2/param3

I have even tried URLHostAllowedCharacterSet, which encodes special characters but not '+' character.

How to encode email containing + character using almofire request?


Solution

  • Try to add an extension to handle the encoding and then just call the extension when you want to encode.

    extension String {
        func stringByAddingPercentEncodingForRFC3986() -> String? {
            let unreserved = "-._~/?:"
            let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
            allowed.addCharactersInString(unreserved)
            return stringByAddingPercentEncodingWithAllowedCharacters(allowed)
        }
    }
    

    And then to use it:

    let query = "http://test.com/param1& param2+ param3"
    let encoded = query.stringByAddingPercentEncodingForRFC3986()!