swift - 从 Alamofire 附加数据不起作用
问题描述
我从 alamofire 获得数据,但它没有附加。我认为这是因为它正在发生异步。只是想不出在我的代码中解决这个问题的最佳方法。在此先感谢您的帮助。
var allItems = [Item]();
@discardableResult func createItem() -> Item {
let newItem = Item(name: "Grocery", description: "Milk Egg Cheese", priority: "High")
// let newItem1 = Item(name: "Test", description: "Tes", priority: "Test")
AF.request("https://mobile-app-i.herokuapp.com/list/list").responseJSON { response in
switch response.result {
case .success(let value):
DispatchQueue.main.async {
if let value = value as? [NSDictionary] {
for d in value {
print(d["description"])
let dataItem = Item(name: d["name"]! as! String, description: d["description"]! as! String, priority: d["priority"]! as! String)
self.allItems.append(dataItem)
}
}
}
case .failure(let error):
print(error)
}
}
// allItems.append(newItem1)
allItems.append(newItem)
return newItem
}
解决方案
通过添加完成块来修复它
AF.request("https://mobile-app-i.herokuapp.com/list/list").responseJSON { response in
switch response.result {
case .success(let value):
DispatchQueue.main.async {
print(type(of: value))
if let value = value as? [NSDictionary] {
completionHandler(value)
}
}
case .failure(let error):
print(error)
}
}
}
像这样打电话
fetchData(completionHandler: {(returnedData)-> Void in
//Do whatever you want with your returnedData JSON data.
//when you finish working on data you can update UI
for (i, d) in returnedData.enumerated() {
print(d["description"])
self.itemStore.createNewItem(name: d["name"]! as! String, description: d["description"]! as! String, priority: d["priority"]! as! String)
}
推荐阅读
- hive - How to retrieve only the latest version of the records from multiple ORC files (via a Hive table) which contain multiple versions for each record?
- sql - 为了避免空白,我应该使用什么来代替顺序?
- php - 有没有办法用 PHPPresentation 下载 pptx 文件?
- eclipse - 如何根据测试用例的状态(通过失败)设置计数器
- reactjs - 如何使用 istanbul 检测代码构建和转译 React 应用程序
- php - 模拟 Laravel 命令依赖
- html - Excel 的 ColorIndex VBA 转换为 HTML 颜色
- php - Yii2 : 创建自定义全局事件
- python - 测试将值插入 mongodb (pyspark, pymongo)
- postgresql - 使用 make 为 Postgresql 创建 pg_strom 扩展时出错:“make: *** No targets specified and no makefile found. 停止。”