简体   繁体   English

Swift中的异步For Loop停止执行?

[英]Async For Loop in Swift halting execution?

I have a big JSON list of items that I download, which I believe happens asynchronously (good) but when I loop through the JSON to turn them into objects ("Product" objects to be exact), the whole app freezes as the for loop executes. 我有一个要下载的项目的JSON列表,我相信这是异步发生的(很好),但是当我遍历JSON将其转换为对象(准确地说是“ Product”对象)时,整个应用程序都会冻结为for循环执行。

The offending call 冒犯性的电话

self.dm.getOrderGuideData({ (time: CFAbsoluteTime) in
     self.dm.parseInOrderGuideProducts({ (completion: Bool) in
     })
})

I put them in closures to prevent this but it doesn't seem to be working. 我将它们封闭起来以防止这种情况,但是它似乎没有用。

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)
    }

Any ideas on how I can fix this? 关于如何解决此问题的任何想法? The output to the console scrolls fine as a the keys are printed (see parseInOrderGuideProducts ) but execution on the phone or simulator halts. 控制台的输出滚动良好,因为会打印出键(请参阅parseInOrderGuideProducts ),但是在电话或模拟器上的执行会暂停。

I solved my problem by explicitly calling the for loop as async using dispatch_async . 我通过使用dispatch_async显式调用for循环作为异步来解决了我的问题。 I then invoke the main thread again for the closure and to change a bool flag of mine. 然后,我再次调用主线程进行关闭操作,并更改我的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM