问题描述
我有一个带有联系人列表的帐户对象,我想要做的是在该postContact之后对嵌套的postAccount进行网络调用。 sideNotes:我们没有批量插入端点,因为我正在使用for循环逐个进入联系人,在循环完成后,有人可以帮助我嵌套调用性能performSegue吗?
func showUIAlertCreate(_ numberOfNewUsers:Int) {
let alert = UIAlertController(title: "Company Created",message: "A new Account has been created and \(numberOfNewUsers) new users have been added.",preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK",style: .default,handler: { action in
DataService.shared.PostAccount("v2","26abd11fb",UUID().uuidString,self.txtfCompanyName.text!,self.dataSource.newContacts,self.stakeholderID,completion: { result in
switch result {
case .success(let account):
dispatchQueue.main.async{
for contact in self.dataSource.newContacts{
DataService.shared.PostContacts("v2",account.accountID,contact,completion: {result in
switch result {
case .success(let result):
break;
case .failure(let error):
fatalError("message: error \(error)")
break;
}
})
self.performSegue(withIdentifier: "seguetoUsersTab",sender: nil)
}
}
break;
case .failure(let error):
fatalError("message: error \(error)")
}
})
}))
self.present(alert,animated: true,completion: nil)
}
解决方法
如果要在完成for循环中的所有操作后执行segue,则必须将Perform segue行移到更像这样的地方。
DispatchQueue.main.async{
for contact in self.dataSource.newContacts{
DataService.shared.PostContacts("v2","26abd11fb",account.accountID,contact,completion: {result in
switch result {
case .success(let result):
break;
case .failure(let error):
fatalError("message: error \(error)")
break;
}
})
// old line here
}
// this will only execute AFTER FOR LOOP
self.performSegue(withIdentifier: "segueToUsersTab",sender: nil)
}