Handling XML data with Alamofire in Swift

Mehmet picture Mehmet · Jun 18, 2015 · Viewed 22.8k times · Source

I started to use cocoapods with my current ios project. I need to use SOAP to get content with easy way for my ios project. I have googled it and Alamofire pod is great for me. Because I am using Swift programming language.

I have inited easily this pod. But my web services return me XML result. And I want to serialisation to array this XML result. But I can't.

When I call my web service with a browser I get this kind of result

enter image description here

Alamofire response method is like this:

Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil)
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }

When I run this method I see this output on the terminal:

<NSMutableURLRequest: 0x170010a30> { URL: http://my-web-service-domain.com }
Optional(<NSHTTPURLResponse: 0x1704276c0> { URL: http://my-web-service-domain.com } { status code: 200, headers {
    "Cache-Control" = "private, max-age=0";
    "Content-Length" = 1020;
    "Content-Type" = "text/xml; charset=utf-8";
    Date = "Thu, 18 Jun 2015 10:57:07 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-AspNet-Version" = "2.0.50727";
    "X-Powered-By" = "ASP.NET";
} })
nil

I want to get result to an array which see on browser to show my storyboard. Can anybody help me how to serialise this data with Alamofire framework or Swift language?

Answer

tsaiid picture tsaiid · Jun 22, 2015

If I did not misunderstand your description, I think you would like to get the XML data and parse it, right? Regarding to this, you may handle with wrong variables in the response callback. You should println(data) to check the XML document.

For parsing XML data, you could consider SWXMLHash. The Alamofire request could look like:

Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil)
         .response { (request, response, data, error) in
            println(data) // if you want to check XML data in debug window.
            var xml = SWXMLHash.parse(data!)
            println(xml["UserDTO"]["FilmID"].element?.text) // output the FilmID element.
         }

Further information about XML management, please check SWXMLHash.