[英]Async For Loop in Swift halting execution?
我有一个要下载的项目的JSON列表,我相信这是异步发生的(很好),但是当我遍历JSON将其转换为对象(准确地说是“ Product”对象)时,整个应用程序都会冻结为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
),但是在电话或模拟器上的执行会暂停。
我通过使用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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.