EzDevInfo.com

SWXMLHash

Simple XML parsing in Swift

Parse XML request in Swift

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?


Source: (StackOverflow)

Can't return value parsing XML using SWXMLHash in Swift

When I try to show "50%", which is taken from

forecast > area > forecast-period > text > probability_of_precipitation

it comes up with "nil" on my label in the storyboard.

I have this snippet of XML, which is located at a public ftp address (shown in my code below)

<forecast>
        <area aac="VIC_FA001" description="Victoria" type="region"/>
        <area aac="VIC_PW001" description="Mallee" type="public-district" parent-aac="VIC_FA001"/>
        <area aac="VIC_PT043" description="Mildura" type="location" parent-aac="VIC_PW001">
            <forecast-period index="0" start-time-local="12pm" end-time-local="12:30pm" start-time-utc="1:00pm" end-time-utc="1:30pm">
                <element type="forecast_icon_code">16</element>
                <text type="precis">Shower or two. Possible storm.</text>
                <text type="probability_of_precipitation">50%</text>
            </forecast-period>
        </area>
</forecast>

And here is my code:

let urlStringMax = "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml"

    if let urlMax = NSURL(string: urlStringMax)
    {
        if let data = try? NSData(contentsOfURL: urlMax, options: [])
        {
            let xml = SWXMLHash.parse(data)

            let precipForecast = xml["forecast"]["area"][2]["forecast-period"][0]["text"][type="probability_of_precipitation"].element?.text

            maxTemp.text = "\(precipForecast)"
        }
    }

Source: (StackOverflow)

Advertisements