如何在异步迭代中设置 DispatchGroup?

How to set up DispatchGroup in asynchronous iteration?(如何在异步迭代中设置 DispatchGroup?)

本文介绍了如何在异步迭代中设置 DispatchGroup?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置用于下载图像的迭代.整个过程正常,但看看控制台的输出,似乎有问题.

I´m trying to set up an iteration for downloading images. The whole process works, but taking a look in the console´s output, something seems to be wrong.

func download() {

    let logos = [Logos]()
    let group = DispatchGroup()

    logos.forEach { logo in

        print("enter")
        group.enter()

        if logo?.data == nil {

            let id = logo?.id as! String

            if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/(id).png") {

                print(checkedUrl)

                LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in

                    logo?.data = data
                    print("stored")

                    group.leave()
                    print("leave")
                }
            }
        }
    }

    print("loop finished")
}

输出:

enter
http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/sd.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/hd.png
loop finished
stored
leave
stored
leave
stored
leave
stored
leave

看起来迭代根本不关心进入和离开 DispatchGroup().网络请求几乎同时被触发.在我看来,输出应该是这样的:

It looks like the iteration does not care about entering and leaving the DispatchGroup() at all. The webrequests are fired almost at the same time. In my opinion the output should look like this:

enter
http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
stored
leave
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
stored
leave
...
loop finished

我监督了什么?能得到一些想法会很棒.

Did I oversee something? Would be awesome to get some ideas.

推荐答案

这个呢:

group.notify(queue: .main) {
print("loop finished")
}

而不是您的正常打印.

func download() {

let logos = [Logos]()  // NSManagedObject
let group = DispatchGroup()

logos.forEach { logo in


    if logo?.data == nil {
        let id = logo?.id as! String
        if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/(id).png") {

            print(checkedUrl)
             print("enter")
            group.enter()
            LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in
                //this is async I think

                coin?.logo = data
                print("stored")

                group.leave()
                print("leave")
            }
        }
    }
}

group.notify(queue: .main) {
print("loop finished")
}
}

这篇关于如何在异步迭代中设置 DispatchGroup?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在异步迭代中设置 DispatchGroup?

基础教程推荐