Search code examples
iosswiftalamofire

Append object to a variable


I'm trying to append an object to an array of objects.

var products: [Product] = []

init() {
    Alamofire.request(.GET, Urls.menu).responseJSON { request in
        if let json = request.result.value {
            let data = JSON(json)

            for (_, subJson): (String, JSON) in data {
                let product = Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)

                print(product)

                self.products.append(product)
            }
        }
    }

    self.products.append(Product(id: 1, name: "test", description: "description", price: 1.0))

    print(self.products)
}

I'm doing a loop through my JSON response and creating the Product object, but when I try to append to products variable, it doesn't append.

Here is the Output:

[Checkfood.Product]
Checkfood.Product
Checkfood.Product
Checkfood.Product
Checkfood.Product
Checkfood.Product

The first line represents the print(self.products) and the rest is print(product)

Thank you


Solution

  • "Networking in Alamofire is done asynchronously" says the API description meaning instead of waiting for response from the server, it calls the handler when response is received but in the meantime code execution continues no matter what. and when the handler is called, the response is accessible only in that handler:- "The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler"

    You can use high priority thread if you want the handler to have that priority. Here is how to do that:

    Alamofire.request(.GET, Urls.menu).responseJSON { request in
        if let json = request.result.value {    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
                let data = JSON(son)
                var product: [Products] = []
    
                for (_, subJson): (String, JSON) in data {
                    product += [Product(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].doubleValue)]
    
                    print(product)
                }
                dispatch_async(dispatch_get_main_queue()) {
                    self.products += product //since product is an array itself (not array element)
                    //self.products.append(product)
                }
            }
        }
        self.products.append(Product(id: 1, name: "test", description: "description", price: 1.0))
    }