ios - 立即调用 DispatchGroup notify() - 不等待进入/离开

标签 ios swift

我已经被这个问题困扰了一段时间,而且我用完了有用的谷歌搜索结果。

我有两个请求,第一个请求从服务器检索一些链接,在另一个请求中我从链接下载图像。所有图片下载完成后,我将结果返回给 View Controller 。

从 UIViewController 调用代码 requestBanners(),进入调度组。理论上,在离开调度组之前,应该为我从服务器获得的每个 url 调用 storeImage(),并且在每次调用时它都应该进入和离开调度组,将图像添加到数组中.一旦完成所有图片的下载,它就会离开调度组,并触发 notify() 以在 UIViewController 上执行 setUpCollection()

使用 print() 作为查看实际情况的指南,我得到:

I'm downloading the urls

Now I'm in the UIViewController (this print() is called in the implementation of setUpCollection())

I'm downloading an image

当它实际上应该下载 url,然后下载图像,然后才返回 UIViewController

我一开始使用信号量,但后来我认为使用调度组会是一个更简洁的解决方案。

在这两种方法中,在完成图像下载之前返回空的 bannersArr。也许那张紧凑的 map 把一切都搞砸了。

代码如下:

class BannersHelper {
    
    private var bannersArr: [UIImage] = []
    private let dispatchGroup = DispatchGroup()
    private var delegate: LoadBanners? = nil
    
    init(delegate: LoadBanners) {
        self.delegate = delegate
        
        dispatchGroup.notify(queue: .main) {
            self.delegate?.setUpCollection(errImg: self.bannersArr)
        }
    }
    
    func requestBanners() {
        print("I'm downloading the urls\n")
        self.dispatchGroup.enter()
        ServiceParametria.getBanners(handler: { response in
            guard let bannersResponse = response as? BannerModel else {
                return
            }
            
            let banners = bannersResponse.data as! [DataBannerModel]
            let _ = banners.compactMap({self.storeImage(model: $0)})
            self.dispatchGroup.leave()
        })
    }
    
    private func storeImage(model: DataBannerModel) {
        print("I'm downloading an image\n")
        self.dispatchGroup.enter()
        ServiceParametria.getImage(url: model.urlImagen!, handler: { result in
            let image = result as! UIImage
            self.bannersArr.append(image)
            self.dispatchGroup.leave()
        })
    }
}

是否有更好的方法来做到这一点,还是我只是错误地使用了调度组?

最佳答案

正如@pkamb 在评论中指出的那样,问题是我试图在 init() 方法中触发 dispatchGroup.notify()

在执行的那个时候,因为我还没有调用 requestBanners(),DispatchGroup 计数器等于零,这导致了对 delegate 的提前调用? .setUpCollection() 带有一个空数组。

dispatchGroup.notify() block 移动到 requestBanners() 方法的末尾解决了问题:)

关于ios - 立即调用 DispatchGroup notify() - 不等待进入/离开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63907835/

相关文章:

ios - 如何更改 uiscrollview ios 中滚动指示器的宽度?

ios - popover改变位置起点(原点位置)iOS9

ios - 更改 tableView 中所有单元格的所有对象的 bool 状态

ios - CompileXIB com.apple.InterfaceBuilder 错误 2001 操作无法完成

ios - 如何从网上下载图片?

ios - GCDAsyncSocket 与 bonjour 服务 : does startTLS initiate TLS handshake

ios - NSString 保留计数 -1

ios - 如何定义自定义 NSUnderlineStyle

iOS 11 Swift 4 iPhone X Safe Area 支持全屏ScrollView

ios - UITabbar 背景图像重复本身