Aditya Sharma
Aditya Sharma

Reputation: 605

Closure gets lost while using dispatch group

Dispatch code not calling.When I call reLog() method it is not executing the code written in DispatchQueue.main.async block.

       func reLog() -> Bool {
            var isVerified = false
            let group = DispatchGroup()
            group.enter()
            DispatchQueue.global(qos: .default).async {
                    self.login({ () -> Void in
                        isVerified = true
                        group.leave()
                    }, fail: { (failureDict) -> Void in
                        group.leave()
                    })
                }
            group.wait() 
            return isVerified
        }


        func login(_ success : (()-> Void), fail : (()-> Void)){
             let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
             let task = session.dataTask(with: urlRequest){
                (data, response, error) -> Void in
                  DispatchQueue.main.async(execute: { () -> Void in
                       print("Testing")   // This closure not calling
                  })
             })
             task.resume()
        }

Now it 's my requirement to to this. I need to implement this because I need server response to continue the loop.

for i in strings {
     let isLogged = relog()
     if isLogged {
        print("Successful")
    }
}

Upvotes: 1

Views: 328

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100533

You need inside login

task.resume()

Replace

group.wait() 
return isVerified

with

group.notify(queue:.main) {
  completion(isVerified)
}

And

func reLog(completion:@escaping(Bool) -> ())

Edit

func reLog(completion:@escaping(Bool) -> ())
            var isVerified = false
            let group = DispatchGroup()
            group.enter()
            DispatchQueue.global(qos: .default).async {
                    self.login({ () -> Void in
                        isVerified = true
                        group.leave()
                    }, fail: { (failureDict) -> Void in
                        group.leave()
                    })
                }
        group.notify(queue:.main) {
          completion(isVerified)
        } 
 }

call

 reLog {  isVerified in
   print(isVerified)
 }

Upvotes: 2

vadian
vadian

Reputation: 285150

The closure is not called because you set the delegate of the URLSession to self which requires to adopt the protocol and implement the delegate methods.

Use the init method with nil delegate

let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) {

And you are misusing DispatchGroup to make an asynchronous task synchronous. That's very bad practice.

Upvotes: 0

Related Questions