我想找到一種方法在Swift中從Web數據中提取多個項目。我期待調用的URL後迅速提取從以下XML數據驅動器的ID:關於從Web數據中提取信息的建議(Swift)
查看源代碼:http://ergast.com/api/f1/current/last/results(在Chrome瀏覽查看源代碼)
目前,我有一個解決方案,只挑選出第一值。理想情況下,我想挑選所有的值並將它們排列在一個數組中供以後使用。
var wasSuccessful = false
let attemptedUrl = NSURL(string: "http://ergast.com/api/f1/current/last/results")
if let url = attemptedUrl {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let urlContent = data {
let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
let websiteArray = webContent?.componentsSeparatedByString("<Driver driverId=\"")
if websiteArray!.count > 1 {
let driverArray = websiteArray![1].componentsSeparatedByString("\" code=")
if driverArray.count > 1 {
wasSuccessful = true
let driverSummary = driverArray[0]
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.lblDrivers.text = driverSummary // just to confirm drivers are showing up
})
}
}
}
if wasSuccessful == false {
self.lblDrivers.text = "Sorry, we could not find the results."
}
}
task.resume()
} else { //if url couldnt be created
self.lblDrivers.text = "Sorry, we could not find the results."
}
}
這工作完美,謝謝花時間寫一個解決方案,我現在應該能夠使用收集的驅動程序數據 – qwerty567111