2016-10-07 54 views
0

我对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%的所有呼叫已经结束。任何帮助?

+1

只是一个想法:对于每个设备响应增加一个计数器,并检查计数器是否等于'devices.count',当值相等时,您知道所有设备已更新,您可以调用您的完成块。 – Laffen

回答

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

每个设备立即进入集团,但直到接收到响应不离开组。直到所有对象都离开组后,才会调用最后的通知块。

+1

太棒了!感谢兄弟 –

+1

我想你想把'notify'调用移到for循环的OUTSIDE。 –

相关问题