Swift 同步发送多个 HTTP POST 请求

标签 swift grand-central-dispatch

在我的代码中,我需要根据用户选择(用户选择图片,每个命令包含一张图片)向服务器发送多个 HTTP POST 命令。

我需要首先通过 HTTP POST 发送文档,然后发送图片的 HTTP POST,最后提交最后一个 HTTP POST。目前它工作得几乎正常,但是如果发送了太多 HTTP POST 命令//我会遇到一些 HTTP 错误(例如发送了 21 张中的 16 张图片)

因此,我想确保在前一个命令发送成功后,每个 HTTP 命令都将一一发送到服务器。

这是我正在使用的代码:

            self.sendDocument{ (response) in
            if let result = response as? Bool {
                if(result == true){
                    self.Documentsent = true

                    print("Document sent, now sending photos")
                    progressDownload.progress = 0.3
                    var i = 0;
                    var j = 0;
                    //now we are sending the Photos !
                    for it in selectedPictures.sharedInstance.selectedCells{

                        let fileName = PhotoGallery.sharedInstance.photoGallery[it.item].fileName
                        self.constatImage = self.getSavedImage(named: fileName!)!

                        self.semaphore.signal()
                        self.envoiPhoto(obj: PhotoGallery.sharedInstance.photoGallery[it.item], pic: self.constatImage, num: it.item){ (result) -> () in
                            print("Envoi Photo \(it.item): \(result)")

                            print("i: \(i), count: \(selectedPictures.sharedInstance.selectedCells.count)")
                            _ = self.semaphore.wait(timeout: DispatchTime.distantFuture)
                            if(i == selectedPictures.sharedInstance.selectedCells.count-1){
                                print("for loop all pictures are sent")
                                self.allPhotosSent = true
                                self.myGroup.leave()
                            }
                            i = i+1

                        }
                        if(progressDownload.progress != 0.8){
                            progressDownload.progress += 0.2
                        }

                        j = j+1;

                    }
                }
                    //Case when document sending is failed
                else{
                    self.Constatsent = false
                }

            }
        }

        self.myGroup.notify(queue: .main, execute: {
            print("in notify: we have sent all the pictures")
            if(self.Documentsent && self.allPhotosSent){
                alertController.dismiss(animated: true, completion: ({
                    if(Constat.sharedInstance.type == "4"){
                        sleep(2)
                        self.envoiCommit()
                    }
                    self.envoiSuccess()
                }))
            }
            else{
                print("error")
                alertController.dismiss(animated: true, completion: ({
                    self.envoiError()
                }))
            }

        })

目前我有以下行为:

  • 发送 HTTP POST 文档
  • HTTP POST 文档完成后,将发送整个 HTTP POST 照片
  • 发送整个 HTTPO POST 照片后,也会发送 HTTP POST 提交。

但我想获取一张一张发送的 HTTP POST 照片。

我怎样才能实现这个目标?

编辑1

我还尝试像这样使用信号量和调度程序:

var i: Int = 0

    let dispatchGroup = DispatchGroup()
    let dispatchQueue = DispatchQueue(label: "test")
    let dispatchSemaphore = DispatchSemaphore(value: 0)

    DispatchQueue.main.async{
        while(i<50){
            dispatchGroup.enter()
                print("This is a synchronized closure iteration: \(i)")
            self.dummyHTTPPOST{ (response) in
                if let result = response as? Bool {
                    if(result == true){
                        print("HTTP POST Sent")
                        dispatchSemaphore.signal()
                        dispatchGroup.leave()
                    }}
            }
            print("round finished")
            dispatchSemaphore.wait()
            i = i+1;

        }
    }

但是方法 dummyHTTPPOST() 中的 HTTP 请求永远不会发送....session.DataTask 永远不会启动。

最佳答案

我终于找到了使用 session.DataTask 同步发送多个 HTTP POST 命令的解决方案。

解决方案如下:

        var i: Int = 0
    let dispatchSemaphore = DispatchSemaphore(value: 0)

    DispatchQueue.global(qos: .userInitiated).async{
        while(i<500){
            self.dispatchGroup.enter()
            print("-------------------------------------------------------------------------")
                print("This is a synchronized iteration: \(i)")
            self.dummyHTTPPOST{ (response) in
                if let result = response as? Bool {
                    if(result == true){
                        print("HTTP POST Sent")
                        dispatchSemaphore.signal()
                    }}
            }
            print("round finished")
            dispatchSemaphore.wait()
            if(i == 49){
                print("sent all HTTP Commands")
                self.dispatchGroup.leave()
            }
            i = i+1;

        }

        DispatchQueue.main.async {
            print("************************")
            print("everything has been sent in Dispatch Queue")
            print("************************")
        }
    }

希望对其他人有帮助。

关于Swift 同步发送多个 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449058/

相关文章:

ios - 通过 Core Image 框架复制结果 `func masking(_ mask: CGImage) -> CGImage?`

swift - 正确使用 Firebase Cloud Functions 和 Stripe

ios - regiondidchange 在 app load swift 上多次调用

ios - 在 dispatch_get_main_queue() 上更新 UI

ios - dispatch_queue 名称和线程

swift - 迁移到 Swift 2 "Use of unresolved identifier ' ** *'"

ios - iOS 8 上未返回正确的自动布局宽度

objective-c - Grand Central Dispatch 延迟执行设计模式

ios - 如何让 dispatch_async 运行

swift - EXC_BAD_INSTRUCTION 在 ios 7(swift) 上使用 dispatch_get_global_queue 时发生