skip to Main Content

I have two parallel & independent functions named function a() ->Bool & function b() ->Bool
Now If any of this function fails I want to show alert box

Note: I can not put one function into another. both func can take ~5 second to complete

Tried approach: created two flag inside a() & b() named var aCompleted: Bool var bCompleted
&

func showAlert() {
if aCompleted && bCompleted {
 // show UIAlertController....
}

I am looking for better approach, Please guide.

2

Answers


  1. Easiest approach would be to use Dispatch Groups.

    let dispatchGroup = DispatchGroup()
        var aSuccess = false
        var bSuccess = false
    
        dispatchGroup.enter()
        DispatchQueue.global().async {
            aSuccess = self.a()
            dispatchGroup.leave()
        }
    
        dispatchGroup.enter()
        DispatchQueue.global().async {
            bSuccess = self.b()
            dispatchGroup.leave()
        }
    
        dispatchGroup.notify(queue: .main) {
            if !aSuccess || !bSuccess {
                self.showAlert()
            }
        }
    

    The .notify function is called only when both the functions have been executed.

    Login or Signup to reply.
  2. func a() async throws -> Bool {
     ....
    }
    
    func b() async throws -> Bool {
    ....
    }
    
    do {
     const boolA = try await a()
     const boolB = try await b()
      if (boolA && boolB) {
      //show alert
     }
    } catch {
    print("Failed with error (error)")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search