Lê Khánh Vinh Lê Khánh Vinh - 1 month ago 7x
Swift Question

swift contsruct a request with xml request body

hi I'm about to create a custom request in swift

I'm having problem with my request body.

This my body in xml:

<ItemTrackingDetailsRequest xmlns="http://singpost.com/paw/ns">

how to convert it to string and then data for the request?

I have try

let params = "<ItemTrackingDetailsRequest>

let xmlRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
xmlRequest.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
xmlRequest.HTTPMethod = "POST"
xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type")

but have error in the params because i construct body String wrongly. Any way to construct String from xml above? any help is much appreciate. THanks


Swift doesn't support multi-line string literal yet and I haven't seen any proposal in the pipeline for that either. If you make that request a lot, it's better to wrap your request in a structure that builds the XML for you:

struct ItemTrackingRequest {
    var trackingNumbers: [String]

    init(trackingNumbers: String...) {
        self.trackingNumbers = trackingNumbers

    func xmlString() -> String {
        var xml = "<?xml version=\"1.0\"?>"
        xml += "<ItemTrackingDetailsRequest xmlns=\"http://singpost.com/paw/ns\">"
        xml += "<ItemTrackingNumbers>"

        for number in self.trackingNumbers {
            xml += "<TrackingNumber>\(number)</TrackingNumber>"

        xml += "</ItemTrackingNumbers>"
        xml += "</ItemTrackingDetailsRequest>"

        return xml

let params = ItemTrackingRequest(trackingNumbers: "SMT0000000628").xmlString()

If you request gets complicated (like a lot more complicated), use Core Data to model the request and generate the XML for there.