-2

Implementing solution given here How to make a synchronous request using Alamofire?

I don't get any errors, it just doesn't work as expected. In tableViewController

override func viewDidLoad() {
    super.viewDidLoad()

    loadData() { (didCompleteRequest) in
        if (didCompleteRequest) {
            self.TodosTableView.delegate = self
            self.TodosTableView.dataSource = self
            print("loading successfull")
        } else {
            print("loading failed")
        }
    }
    print("leaving viewDidLoad")
}

func loadData(completion: @escaping (Bool) -> Void) {
    Alamofire.request(TodosViewController.serverAdress + "projects/index.json").responseJSON { response in
        do {
            // async stuff
        } catch {
            completion(false)
        }
        print("leaving loadData")
        completion(true)
    }
}

output I get

leaving viewDidLoad

leaving loadData

loading successfull

apparently, the first element should be the last one

Alexander Kozachenko
  • 885
  • 2
  • 13
  • 26
  • This is async request so it will not wait to finish your `loadData` so it is moving to `leaving viewDidLoad` – Prashant Tukadiya Feb 10 '18 at 13:38
  • Unrelated but you have to add a `return` statement in the `catch` clause to avoid calling the completion closure twice. The order of the output is correct as the closure in the `loadData()` method returns its data later asynchronously. – vadian Feb 10 '18 at 13:40
  • @vadian nope, I'll add, thanks. – Alexander Kozachenko Feb 10 '18 at 13:43
  • @vadian Better yet, move the stuff (at least that 2nd `completion` call) that is after the do/catch block inside the `do` block. – rmaddy Feb 10 '18 at 16:41

2 Answers2

1

First viewDidLoad is running in the main thread. So when you put this loadData() in viewDidLoad controls dispatched to background thread where alamofire works on, and the main thread continues and prints leaving viewDidLoad

Try this

 override func viewDidLoad() {
super.viewDidLoad()

  self.TodosTableView.delegate = self
  self.TodosTableView.dataSource = self

loadData() { (didCompleteRequest) in
    if (didCompleteRequest) {           
        self.TodosTableView.reloadData()
        print("loading successfull")
    } else {
        print("loading failed")
    }
}
print("leaving viewDidLoad")
}
Rizwan Ahmed
  • 919
  • 13
  • 19
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
-1

You are call block code after get response from server. so first call "print("leaving viewDidLoad")".

response code get with delay so call block code with delay

Moosa
  • 89
  • 1
  • 8