0

I have the following code using SWXMLHash - the XML parser however does not appear to be able to process it. I have checked the URL to make sure it returns data:

let baseUrl = "http://apps.hha.co.uk/mis/Api/getlivesensors.aspx?key=6fb21537-fb4e-4fe4-b07a-d8d68567c9d1"
        var request = URLRequest(url: NSURL(string: baseUrl)! as URL)
        let session = URLSession.shared
        request.httpMethod = "GET"

        //var err: NSError?

        let task = session.dataTask(with: request as URLRequest) {
            (data, response, error) in

            if data == nil {
                print("dataTaskWithRequest error: \(error)")
                return
            }

            let xml = SWXMLHash.parse(data!)

            if (xml["Sensors"]["Sensor"]["Name"].element?.text) != nil
            //if (xml["Sensors"]["Sensor"]["Name"].element?.text) != nil 
            {
                self.sensors.add(xml["Sensors"]["Sensor"]["Name"].element?.text as Any)
            }

            DispatchQueue.main.async(execute : {
                print(self.sensors)
            })

        }
        task.resume()
        // but obviously don't try to use it here here

The XML I get from the url is like this (tags are closed off - I just haven't included them):

<Sensors>
<Sensor>
<ID>12</ID>
<Name>EFM W.level</Name>
<Series>Level</Series>
<Unit>m</Unit>
<Values>
<Value CreatedOn="2017-01-08T13:50:00" Value="0.69"/>
<Value CreatedOn="2017-01-08T14:00:00" Value="0.72"/>
<Value CreatedOn="2017-01-08T14:10:00" Value="0.77"/>
<Value CreatedOn="2017-01-08T14:20:00" Value="0.82"/>
<Value CreatedOn="2017-01-08T14:30:00" Value="0.87"/>

A view of the local variables as the app runs

HillInHarwich
  • 441
  • 6
  • 25
  • Piece by piece: `xml["Sensors"]` returns something? if YES, `xml["Sensors"]["Sensor"]` too? if yes, `xml["Sensors"]["Sensor"]["Name"]` ? etc. – Larme Jan 09 '17 at 15:06
  • The xml variable doesn't have any data in it after parsing. – HillInHarwich Jan 09 '17 at 15:08
  • This is what I get when I try to print the value of XML: Printing description of xml: expression produced error: error: /var/folders/z0/gvxkyn_x3d18qbkml14_wngc0000gn/T/./lldb/42932/expr33.swift:1:75: error: 'XMLIndexer' is not a member type of 'SWXMLHash' Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer(bitPattern: 0x1045a4290)!.pointee) – HillInHarwich Jan 09 '17 at 15:17
  • I have the same problem, how you solved this ? – Roei Nadam Dec 04 '18 at 06:26

2 Answers2

1

There are multiple Sensor elements but only one Sensors element.

So, instead of:

xml["Sensors"]["Sensor"]["Name"].element?.text

You should have something like:

xml["Sensors"]["Sensor"][0]["Name"].element?.text

That would grab the first sensor out of the group that is returned.

To loop over the sensors, you'll have something like:

for sensor in xml["Sensors"]["Sensor"].all {
    sessors.add(sensor["Name"].element?.text)
}

Hope this helps!

David Mohundro
  • 11,922
  • 5
  • 40
  • 44
0

OK. I have solved the problem. The issue was with the XML file i receive from the server. It looks like it is UTF-8 format, but the document says it is UTF-16. So, I now convert the data object received into a UTF-8 NSString, and then cast that into a String! Please see the code below:

    let baseUrl = "http://apps.hha.co.uk/mis/Api/getlivesensors.aspx?key=6fb21537-fb4e-4fe4-b07a-d8d68567c9d1"
    var request = URLRequest(url: NSURL(string: baseUrl)! as URL)
    let session = URLSession.shared
    request.httpMethod = "GET"

    let task = session.dataTask(with: request as URLRequest) {
        (data, response, error) in

        if data == nil {
            print("dataTaskWithRequest error: \(error)")
            return
        }

        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)?.replacingOccurrences(of: "utf-16", with: "utf-8")

        let xml = SWXMLHash.parse(dataString! as String)
        //let xml = SWXMLHash.parse(dataString!)

        if (xml["Sensors"]["Sensor"][0]["Name"].element?.text) != nil
        {
            self.sensors.add(xml["Sensors"]["Sensor"][0]["Name"].element?.text as Any)
        }

        DispatchQueue.main.async(execute : {
            print(self.sensors)
        })

    }
    task.resume()
    // but obviously don't try to use it here here
HillInHarwich
  • 441
  • 6
  • 25