skip to Main Content

I have the code below that I use using a "DispatchGroup":

// class variables
let myUploadGroup = DispatchGroup()
var concatenatedUploadGroupMessage:String = ""

// inside a method I have the code below
for resFoto in resFotosResenhaEscolhidas {
        
        myUploadGroup.enter()
        
        jsonRequestUploadImagem = ResFotosModel.createJsonFotoResenha(resFoto, resenhaDados.IdGedave)
                    
        let requestUploadImagem: NSMutableURLRequest = serviceRepository.clientURLRequest(wsUploadImagem, typeAutho: .basic, parms: "", body: jsonRequestUploadImagem as Dictionary<String, AnyObject>)
        
        serviceRepository.post(requestUploadImagem, retryLogin: true, completion: {isOk,msgError,httpCode,needLogin,response in
            self.checkResponseUploadImagemFotoResenha(response as AnyObject, httpCode)
        })
        
    }

func checkResponseUploadImagemFotoResenha(_ response:AnyObject, _ httpCode:Int) {
    
    if httpCode != 200 {
        let string = String(data: response as! Data, encoding: .utf8)
        print( string!+" n Erro HTTP: "+String(httpCode) )
        myUploadGroup.leave()
        AlertActions.showBasicAlert(erroParaExibir: string!+" n Erro HTTP: "+String(httpCode), currentView: self)
    } else {
        // httpCode == 200
        let data: Data = response as! Data // received from a network request, for example
        
        let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: [])
        
        guard let dictionary = jsonResponse as? [String: Any] else { return }
        guard let nestedDictionary = dictionary["RetornoGravacaoImagemWSVO"] as? [String: Any] else { return }
        
        let mensagem = nestedDictionary["mensagem"] as! String
        let codigo = nestedDictionary["codigo"] as! Int
        
        
        if codigo != 200 {
            print("Erro upload foto - codigo: (codigo)")
            concatenatedUploadGroupMessage = concatenatedUploadGroupMessage+" (mensagem) - (codigo) n"
        } else {
            let nomeArquivo = nestedDictionary["nomeArquivo"] as! String
            concatenatedUploadGroupMessage = concatenatedUploadGroupMessage+" (nomeArquivo) - (mensagem) n"
        }
        
        
        myUploadGroup.leave()
    }
    
    myUploadGroup.notify(queue: DispatchQueue.main) {
        AlertActions.showBasicAlert(erroParaExibir: self.concatenatedUploadGroupMessage, currentView: self)
        print("Finished all requests.")
        CustomLoadingBar.hide(self) // use in conjunction with the Grand Dispatcher Group
    }
    
    
}

I use "myUploadGroup.enter()" and "myUploadGroup.leave()" to send the signal to start and end the request.

After that I have the method "myUploadGroup.notify".

When all request are made, for example, 4 http requests are started and when they finish I can see the message "Finished all requests." print 4 times in the console.

What I want to do is when the 4 http requests are finished, I only want to see the message message "Finished all requests." printed once on the console instead of seeing the message printed 4 times.

How can I do that?

2

Answers


  1. Chosen as BEST ANSWER

    I was able find a solution to my problem without the need to rewrite my code to queue up my requests.

    I create a class variable

    var counter:Int = 0
    

    Before my "myUploadGroup.enter()" function I add the following code

    counter = counter + 1
    

    In my "myUploadGroup.notify" function I add this code

    self.counter = self.counter - 1
    if self.counter == 0 {
       print("I run once")
    }
    

    It works for me now.


  2. You are calling myUploadGroup.notify() in your function checkResponseUploadImagemFotoResenha(), which is called from your completion handler. That means you are calling myUploadGroup.notify() more than once. Don’t do that.

    Rewrite your code that queues up your requests like this:

    for requestInfo in requests {
        myUploadGroup.enter()
        submitRequest( completion: {
           // Process response
           myUploadGroup.leave()
    }
    
    myUploadGroup.notify(queue: DispatchQueue.main) {
       // Code to execute once when all the requests have completed
    }
    

    Note how I put the call to notify after the loop that submits the requests.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search