Append object to a variable

谁说胖子不能爱 提交于 2019-12-02 09:41:27

"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))
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!