我有一个很大的JSON列表,我下载的项目,我相信是异步(好),但当我循环通过JSON将它们变成对象(“产品”对象准确),整个应用程序冻结为for循环执行。
违规电话
self.dm.getOrderGuideData({ (time: CFAbsoluteTime) in
self.dm.parseInOrderGuideProducts({ (completion: Bool) in
})
})
我把它们放在封闭物中以防止这种情况,但它似乎没有起作用。
func getOrderGuideData(completion: (time: CFAbsoluteTime) -> ()) {
let startTime = CFAbsoluteTimeGetCurrent()
Alamofire.request(.POST, "https://sysco-dev.madmobile.com/api/products.pricing", parameters: orderGuideRequest, encoding: .JSON) .responseJSON { (req, res, json, error) in
if error != nil {
println("\n\nOG ERROR: \(error!)\n\n")
println(req)
println(res)
let endTime = CFAbsoluteTimeGetCurrent() - startTime
completion(time: endTime)
}
else {
var jsonForError = JSON(json!)
if jsonForError["errors"] != nil {
println("Order Guide Success")
self.rawOrderGuideJSON = json
let endTime = CFAbsoluteTimeGetCurrent() - startTime
completion(time: endTime)
}
else {
var error = jsonForError["errors"]
println(error)
let endTime = CFAbsoluteTimeGetCurrent() - startTime
completion(time: endTime)
}
}
}
}
func parseInOrderGuideProducts(completion: Bool -> ()) {
var parsedJSON = JSON(rawOrderGuideJSON!)
var resultset = parsedJSON["resultset"]
for (key, subJson) in resultset {
println(key)
var newProduct: Product = Product()
newProduct.title = key as String
// newProduct.id = parsedJSON["resultset"][key]["materialId"].string
// newProduct.image = getOrderGuidePhotoForID(newProduct.id!)
newProduct.id = resultset[key]["materialId"].string
var price = resultset[key]["price"].double
newProduct.price = "$\(price!)"
newProduct.weight = resultset[key]["totalWeight"].string
orderGuideItemsList.append(newProduct)
}
completion(true)
}
关于如何解决此问题的任何想法?当打印键时,控制台的输出会正常滚动(请参阅parseInOrderGuideProducts
),但手机或模拟器上的执行会停止。
答案 0 :(得分:0)
我通过使用dispatch_async
显式调用for循环作为异步来解决我的问题。然后我再次调用主线程进行闭包并更改我的bool标志。
func parseInOrderGuideProducts(completion: Bool -> ()) {
var parsedJSON = JSON(rawOrderGuideJSON!)
var resultset = parsedJSON["resultset"]
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
for (key, subJson) in resultset {
println(key)
var newProduct: Product = Product()
newProduct.title = key as String
newProduct.id = resultset[key]["materialId"].string
var price = resultset[key]["price"].double
newProduct.price = "$\(price!)"
newProduct.weight = resultset[key]["totalWeight"].string
newProduct.image = self.getOrderGuidePhotoForID(newProduct.id!)
self.orderGuideItemsList.append(newProduct)
}
dispatch_async(dispatch_get_main_queue()) {
completion(true)
self.finishedPopulatingOrderGuide = true
}
}
}