2

I have to wait for the completion until the user touches the Try Again button to call the same function again. All works fine the first time but when I press it again, the notfy() method doesn't get called. Here is the playground class to simulate that scenario:

import Foundation

class TokenManager{
    private var alertAlreadyShown = false
    static let shared = TokenManager()
    var alreadyEnterGroup = false
    let handlerTryAgainGroup = DispatchGroup()

    func showRefreshAlert(onTryAgainPressed : @escaping()->Void){
        //PREVENTS TO ENTER ON GROUP MUTIPLE TIMES (ASYNC CALLS)
        if(!alreadyEnterGroup){
            alreadyEnterGroup = true
            self.handlerTryAgainGroup.enter()
        }
        //PREVENTS TO SHOW ALERT MUTIPLE TIMES (ASYNC CALLS)
        if(!alertAlreadyShown){
            alertAlreadyShown = true
           //NOTIFY THE COMPLETION THAT USER TOUCH TRY AGAIN BUTTON
            handlerTryAgainGroup.notify(queue: DispatchQueue.main) {
                onTryAgainPressed()
            }
        }else{
            //THIS IS JUST A TEST TO SIMULATE THE USER TAPS MUTIPLE TIMES ON BUTTON
            TokenManager.shared.tryAgainPressed()
        }

    }

    func tryAgainPressed() {
        alreadyEnterGroup = false
        handlerTryAgainGroup.leave()
    }
}

func showAlert(){
    TokenManager.shared.showRefreshAlert {
        //CALLS THE SAME FUNCTION IF THE USER TAPS TRY AGAIN
         showAlert()
     }
}

//SHOW THE ALERT AND PRESS TRY AGAIN FOR THE FIRST TIME
showAlert()
TokenManager.shared.tryAgainPressed()

What is wrong at this case?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
ios_dev
  • 359
  • 2
  • 13
  • 4
    When working with a dispatch group, think of it as a number start at 0. The call to `enter` adds 1. The call to `leave` subtracts 1. A call to `notify` results in the block being called when the count is 0. If your `notify` block isn't being called then you have a mismatch in the class to `enter` and `leave`. – rmaddy Dec 03 '18 at 16:07
  • 1
    But the notify() block it is called correctly at the first time. If we put some prints on the methods, the enter() and leave() are called at the right way. Only the notify() block isn't called at the recursive call. – ios_dev Dec 03 '18 at 16:12
  • 1
    Is the call to `notify` even being reached the 2nd time? `alertAlreadyShown` is probably `true` so you never even attempt to call `notify` a 2nd time. – rmaddy Dec 03 '18 at 16:14
  • 1
    Yep!! Thats right. The var alertAlreadyShown is the problem. But the notify() method isnt a completion from DispatchGroup() ?? Why a local var are changing your behaviour? – ios_dev Dec 03 '18 at 16:18
  • 1
    The `notify` block is only called once per call to `notify`. – rmaddy Dec 03 '18 at 16:19

0 Answers0