kush Thakkar kush Thakkar - 1 month ago 4
Swift Question

Convert String to UTF8String - Swift - iOS - XMLParser

I have this String -

&to[]=0532332028&to[]=0532332027


I want to convert this String to (UTF8) -

%26to%5B%5D%3D0532332028%26to%5B%5D%3D0532332027


I already try this Code -

let str = String(UTF8String: "&to[]=0532332028&to[]=0532332027".cStringUsingEncoding(NSUTF8StringEncoding)!)


Thanks

Answer

To convert the string to UTF8, you can follow the code

    let text = "&to[]=0532332028&to[]=0532332027"
    let encodeText = text.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    print("encodeText : \(encodeText)")

Output : encodeText : &to%5B%5D=0532332028&to%5B%5D=0532332027

But by the above code, you won't get %26 for "&", If you want it You can create a custom method to replace "&" with "%26" by using "stringByReplacingOccurrencesOfString" method.

Hope it helps.

Comments