iosswiftencodingurlsessionmoya

How to encode Swift Arithmetic Operator Plus Sign (+) to utf8 data properly?


I m facing a situation where i need to encode a phone number with country code (like : +959450044651).And add it to a post request body and make a request.after than i face its not encoded property and its seems send string with an empty string for exaample "+959450044651" . how can fix this ?

here is my encoding code

let parameters = "phone=+959450044651"
var postData =  parameters.data(using: .utf8)

i get number with and empty space like :- " 959450044651"

but i need with + Like :- "+959450044651"

enter image description here


Solution

  • You need to percent encode the plus sign. Just replace its occurrences with "%2b". Note that when converting a string to utf8 data it will never fail so you can simply pass its UTF8View utf8 property to the Data initializer:

    let parameters = "phone=+959450044651"
    let postData =  Data(parameters.replacingOccurrences(of: "+", with: "%2b").utf8)