我目前正在尝试使用BEMSimpleLineGraph在swift中创建历史汇率图,并使用AlomoFire从http://fixer.io/获取数据。我使用一个for循环遍历7天(只是为了看看我是否能让它工作),然后将值附加(或其他名称)到一个名为xAxisData的数组中
func updateGraphData(timeInterval: Int){
if selectedCurrency1 != nil && selectedCurrency2 != nil { // checking if both currencies have been selected
self.xAxisData.removeAll() // removing some default values
for i in 1...timeInterval { // don't know exactly if i'm doing this the optimal way?
print("passed")
let date = Date()
let dateComponents = Calendar.current.dateComponents([.month, .day,.year], from: date) //getting the the year(again, just to see if it's working)
historyURL = "http://api.fixer.io/\(dateComponents.year!.description)-03-0\(String(i))?base=\(selectedCurrency1!.rawValue)" //modifying the url to my needs
Alamofire.request(historyURL, method: .get).responseJSON { // requesting data
response in
if response.result.isSuccess{
let json = JSON(response.result.value!)
self.xAxisData.append(json["rates"] [self.selectedCurrency2!.rawValue].doubleValue) // using SwiftyJSON btw to convert, but shouldn't this in theory append in the correct order?
print(json["date"].stringValue) // printing out the date
}
else{
print("Error \(String(describing: response.result.error))")
}
}
}
}
}控制台:
[]
2017-03-02
2017-03-03
2017-03-01
2017-03-03
2017-03-03
2017-03-06
2017-03-07
[4.5359999999999996, 4.5316000000000001, 4.4739000000000004, 4.5316000000000001, 4.5316000000000001, 4.5133000000000001, 4.4844999999999997]我知道我犯了一个错误,我把货币价值变成了双精度,而它可能应该是一个浮点数。如果需要,请随时询问更多信息,或者以任何其他方式更正我的信息,因为我只是在尝试学习。
我希望输出按时间顺序排列,因此日期是1,2,3,4,5,6,7,而不是2,3,1,3,3,6,7。我使用了修改后的多个URL,例如api.fixer.io/2017-03-01?base=GB。
发布于 2017-07-31 20:15:22
问题是所有的网络请求都是异步的,并且不能保证它们将按照它们被调用的顺序完成执行。因此,数组中的数据不是按调用请求的顺序排列的。
您可以使用串行DispatchQueue使您的请求按照您调用它们的顺序运行,但是,这会使您的程序变慢,因为它一次只执行一个请求,而不是并行运行所有请求。
对于这个特定的问题,更好的解决方案是将补全处理程序内部的值插入到数组中的某个索引中,而不是仅仅将它们追加。这样,即使不需要同步API调用,也可以使排序与API调用的顺序相同。或者,您可以将返回值存储在字典中,其中的键将是发出网络请求的日期的字符串表示。
发布于 2017-07-31 20:37:54
struct Rate { let currency : String let date : Date var value : Double }
for循环的数组
日历let
- calculate the date with the `Calendar` API, your way gets in trouble on overflow to the next month. For example= Calendar.current //将日期设置为中午,以避免在午夜更改夏令时。在一些国家/地区,让today = calendar.date(bySettingHour: 12,分钟: 0,秒: 0,of: Date())!让格式化程序= DateFormatter() formatter.dateFormat = "yyyy-MM-dd“用于0...7 {让currentDate = calendar.date(byAdding:.day,value: dayOffset,to: today)!让currentDateAsString = formatter.string(from: currentDate)打印(currentDate,currentDateAsString) }
-从当前日期创建Date。
-创建一个有实际日期和名称的Rate实例,添加到historicalRates中,并传递给异步任务。
value。当循环是finished.historicalRates by 时,DispatchGroup获得通知https://stackoverflow.com/questions/45415182
复制相似问题