The question is not particularly related to Swift UI, the following solution is general.
As I said a few times the received data is CSV (comma separated values), each line is a record, the fields are separated by comma.
To parse the string first create a custom struct
struct ZenithData {
let date : Date
let angle : Double
}
and a data source array
var zenithData = [ZenithData]()
then load the data asynchronously with URLSession
, split the text into lines, split the lines into fields, join the date and time parts and convert it into Date
and populate the array.
Note: The exact date format is ambiguous. The format could be also d/M/yyyy
let url = URL(string: "https://midcdmz.nrel.gov/apps/spa.pl?syear=2020&smonth=1&sday=1&eyear=2020&emonth=1&eday=1&otype=0&step=60&stepunit=1&hr=12&min=0&sec=0&latitude=39.743&longitude=-105.178&timezone=-7.0&elev=1829&press=835&temp=10&dut1=0.0&deltat=64.797&azmrot=180&slope=0&refract=0.5667&field=0")
let dataTask = URLSession.shared.dataTask(with: url!) { data, _, error in
if let error = error { print(error); return }
let string = String(data: data!, encoding: .utf8)!
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "M/d/yyyy H:mm:ss"
let lines = string.components(separatedBy: CharacterSet.newlines)
for i in 1..<lines.count { // first line is dropped
let fields = lines[i].components(separatedBy: ",")
if fields.count != 3 { continue }
let date = dateFormatter.date(from: fields[0] + " " + fields[1])!
let angle = Double(fields[2])!
zenithData.append(ZenithData(date: date, angle: angle))
}
print(zenithData)
}
dataTask.resume()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…