How to know when multiple web calls have ended, to call completion

后端 未结 1 486
借酒劲吻你
借酒劲吻你 2020-12-20 08:47

I\'m fairly new to Swift and this question is probably really stupid. So bear with me please.

I have a collection of devices that I want t

相关标签:
1条回答
  • 2020-12-20 09:28

    I'd suggest using dispatch groups:

    func resetDevice(completion: () -> ()) {
        let dispatchGroup = DispatchGroup()
    
        for device in devices {
    
            dispatchGroup.enter()
    
            device.isValid = 0
    
            DeviceManager.instance.updateDevice(device).call { response in
                print("device reset")
                dispatchGroup.leave()
            }
        }
    
        dispatchGroup.notify(queue: DispatchQueue.main) {
            // Some code to execute when all devices have been reset
        }
    }
    

    Each device enters the group immediately, but doesn't leave the group till the response is received. The notify block at the end isn't called until all objects have left the group.

    0 讨论(0)
提交回复
热议问题