我想找到一种方法在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