0

I need make a web requests and I need that be sync, because my program must continous after login on webserver for example, or download data.

For start, I've a login in my viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    print(NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as String)

    self.waitView.startAnimating()
    self.waitView.hidesWhenStopped = true

    let group = DispatchGroup()

    print("before")

        group.enter()
        OdooAuth.init(successBlock: { (success) in
            print(success)
            group.leave()
            self.waitView.stopAnimating()
        }) { (erro) in
            group.leave()
            self.waitView.stopAnimating()
            print(erro)
        }
    }

    print("before wait")
    group.wait()
    print("after wait")
}

However, this not works. The code keeping locked. I did thinked that when I call group.leave() the code continous below group.wait(). But this not happens and I don't know which way to do this.

Augusto
  • 3,825
  • 9
  • 45
  • 93
  • 2
    Never use `wait` on the main thread. And if `OdooAuth` calls its completion handler on the the main thread, this code will deadlock: You can have the main thread waiting for `OdooAuto` to call a completion on a handler, but that completion handler can't run on the main thread because you're blocking it with a `wait`. – Rob Mar 24 '18 at 20:25
  • The attempted pattern above is "wait and block main thread until network request is done", but that's not advisable (for many reasons). Instead you want a "start asynchronous request and update UI accordingly when it's done" pattern. – Rob Mar 24 '18 at 20:29
  • Yes it's this: "start asynchronous request and update UI accordingly when it's done" pattern. But, how I make this? Because after login, I need download the content, and I need logged to do this. Or better, how the most people make this? – Augusto Mar 24 '18 at 20:33
  • Ok, so, in any case I go need run code in backgroud queue, How I make other function run on No main thread? – Augusto Mar 24 '18 at 20:35
  • This is a discussion about why waiting is a bad idea: https://stackoverflow.com/a/24793935/1271826. This is example of how you'd make a "login" button wait for a network request before proceeding to the next scene: https://stackoverflow.com/a/38620382/1271826. The details here are different than this question, but the concepts are the same, namely never wait or do anything to block the main thread, but instead have the completion handlers initiate the next step of the process. – Rob Mar 24 '18 at 20:50
  • Create Operations (NSOperation) and build dependencies. – user1046037 Mar 25 '18 at 02:20

0 Answers0