微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在for循环Swift中发送响应POST urlsession任务?

如何解决如何在for循环Swift中发送响应POST urlsession任务?

如何在for循环中发送响应POST urlsession任务。我有一个创建“客户和联系人”的视图。我将联系人存储在数组中。我有两个端点postAccount和Postcontacts(notBulkPost);在postAccount之后,我循环抛出列表联系人以将其一一插入。但是该任务仅插入第一个联系人。如何在for循环中发布联系人。

func showUIAlertCreate(_ numberOfNewUsers:Int) {
    let alert = UIAlertController(title: "Company Created",message: "A new company has been created and \(numberOfNewUsers) new users have been added. An email has been sent to these users to complete their account setup.",preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK",style: .default,handler: { action in
        
        DataService.shared.PostAccount("23242-07","2sdfsd",UUID().uuidString,self.txtfCompanyName.text!,self.dataSource.newContacts,completion: {  result in
            
    
            switch result {
                case .success(let account):
                    for index in self.dataSource.newContacts {
                        DataService.shared.PostContacts("23242-07","sdfsdf",account.accountID,index,completion: {  result in
                            
                            switch result {
                                case .success(let data):
                                    print("done!")
                                    dispatchQueue.main.async{
                                        self.performSegue(withIdentifier: "seguetoUsersTab",sender: nil)
                                    }
                                    
                                    break;
                                
                                case .failure(let error):
                                    
                                    fatalError("message: error \(error)")
                            }
                        })
                    }
                    
                    break;
                
                case .failure(let error):
                    
                    fatalError("message: error \(error)")
            }
        })
        
        
    }))
    
    self.present(alert,animated: true,completion: nil)
}

解决方法

尝试DispatchGroup

let dispatchGroup = DispatchGroup()

...
for index in self.dataSource.newContacts {
    dispatchGroup.enter()

    DataService.shared.PostContacts("23242-07","sdfsdf",account.accountID,index,completion: {  result in
        // Do your stuff here
        dispatchGroup.leave()
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。