-1

I get the Data from alamofire however it's not appending. I think the reason for this is because it's happening Async. Just couldn't figure out the best way to fix this in my code. Thanks in Advance for the help.

 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
    }

1 Answers1

0

Fixed it by adding completion block

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

Call like so

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