I have an swift 5 app that posts data to update a mysql table. It works fine except, users noticed that having an ampersand & in the description field would cause app update function to fail.
here is component struct
import Foundation
struct Component: Codable {
var sku, qty, desc, condition: String
enum CodingKeys: String, CodingKey {
case sku = "Sku"
case qty = "Qty"
case desc = "Desc"
case condition = "Condition"
}
}
here is my swift 5 code to create the post parameters
var newCompUpload = [Component]()
newCompUpload.append(newComp)
let jsonData = try! JSONEncoder().encode(newCompUpload)
let uploadData = String(data: jsonData, encoding: .utf8)!
let defaults = UserDefaults.standard
let UserID = defaults.integer(forKey: "UserID")
let postParameters1 = "mode="+mode+"&ShipmentID="+self.ShipmentID
let postParameters2 = "&Contents="+uploadData+"&UserID=\(UserID)"
let postParameters = postParameters1 + postParameters2 // + postParameters3
request.httpBody = postParameters.data(using: String.Encoding.utf8, allowLossyConversion: false)
Here is an example of request.httpBody with an ampersand which breaks the json
mode=saveContents&ShipmentID=8702&Contents=[{"Qty":"1","Sku":"54657","Desc":"test & test","Condition":""}]&UserID=1437
This looks like it should make it to the server ok. But it doesn't. The following is what appears to make it to the server in the raw $_POST['Contents'] parameter
[{"Qty":"1","Sku":"54657","Desc":"test
Obviously broken json at the ampersand. I am not really sure what is breaking it, or if I can change anything in swift delivery to get it to transfer correctly