小编典典

如何知道多个网络通话何时结束,才能完成通话

swift

我是新手Swift,这个问题可能真的很愚蠢。所以请和我一起。

我有一个collection要通过Webservice电话重置的设备。这是我Function现在的样子(尚未完成)

func resetDevice(completion: () -> ()) {
    for device in devices {
        device.isValid = 0
        DeviceManager.instance.updateDevice(device).call { response in
            print("device reset")
        }
    }
}

我不太确定该打电话给我的完成电话,也不确定如何100%确保所有电话都已结束。有什么帮助吗?


阅读 414

收藏
2020-07-07

共1个答案

小编典典

我建议使用调度组:

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

每个设备都立即进入该组,但直到收到响应后才离开该组。在所有对象都离开组之前,不会调用最后的notify块。

2020-07-07