[英]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.