首页 > 解决方案 > 从 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
    }

标签: swiftasynchronousalamofire

解决方案


通过添加完成块来修复它

        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)
              
               
            }

推荐阅读