我有以下使用 SWXMLHash 的代码——但是 XML 解析器似乎无法处理它。我检查了 URL 以确保它返回数据:
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
我从 url 获得的 XML 是这样的(标签已关闭 - 我只是没有包含它们):
<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"/>