循环完成后执行Segue

performSegue after loop is done

我有一个带有联系人列表的帐户对象,我想做的是在 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", "26abd11fb", 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)
}