2

I am just beginning to dabble around with Swift.

I have the following get request using NSURLSession:

let url = NSURL(string: "http://api.bart.gov/api/sched.aspx?cmd=arrive&orig=24th&dest=rock&key=MW9S-E7SL-26DU-VV8V")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in

        println(NSString(data: data, encoding: NSUTF8StringEncoding))

          }

    task.resume()

However, the data is all jumbled up in XML. How do I go about formatting the data in a readable manner?

I am trying to parse the data using this line of code:

let xml = SWXMLHash.parse(data: data)

However, this is giving me an error about not being able to use data. Am I headed in the right direction with the SWXMLHash.Parse function?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
jipot
  • 304
  • 3
  • 13
  • 34
  • 2
    You should look into SwiftyJSON for serializing your JSON response. – pbush25 Jul 20 '15 at 17:52
  • @pbush25 This is what I have so far: let json = JSON(NSString(data: data, encoding: NSUTF8StringEncoding))) However, it is not compiling. Any idea? – jipot Jul 20 '15 at 18:17
  • Or `NSJSONSerialization`. But `SWXMLHash` sounds like it's an XML parser, and XML is a completely different thing. Do you have JSON or XML? – Rob Jul 20 '15 at 18:18
  • @Rob Ahh. Oops! I actually need XML, not JSON. – jipot Jul 20 '15 at 18:23

1 Answers1

2

The syntax for the parse method is without data: label:

let xml = SWXMLHash.parse(data)
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Hi @Rob can you say where should I put the "let xml = SWXMLHash.parse(data)" code ? because i'm stuck in using SWXMLHash to parse xml url – anonymox Jan 04 '16 at 05:58
  • @anonymox Presumably inside your `dataTaskWithURL` completion block (after, of course, you've confirmed that `data` is not `nil`). – Rob Jan 04 '16 at 06:00
  • but it's not parsing the xml data, I don't get any result. this is my code : i appreciate your help, let url = NSURL(string: "http://razavitv.aqr.ir/index/rss/2") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in var xml = SWXMLHash.parse(data!) let count = xml["channel"].all.count } task.resume() – anonymox Jan 04 '16 at 06:06
  • I'd suggest you post your own question, as we're beyond the scope of what we can easily diagnose here. In your question, include a [MCVE](http://stackoverflow.com/help/mcve). – Rob Jan 04 '16 at 06:29
  • I've created my question : http://stackoverflow.com/questions/34586266/not-getting-any-result-parsing-xml-using-swxmlhash – anonymox Jan 04 '16 at 07:13