Search code examples
swiftxcodeasynchronousalamofire

Swift 3: get information from server in ViewDidLoad and when click a button, wait for information response from server


In my app, I want to call an async function (using alamofire) in ViewDidLoad, and user can still interact with the view until he presses a button, and I want the app to show progress hud if the async function is not finished or go to next view if it's finished. I don't want to call the async function on button click, because it may take sometimes and user has to wait longer compare to I call the async function at ViewDidLoad How can I do this?


Solution

  • Edit - use enum to hold the view controller state

    enum State {
        case Loading
        case Ready
        case ShowNext
    }
    var state: State
    
    func viewDidLoad() {
      state = .Loading
      makeAsyncCall() { (finished) in 
         if state == .ShowNext {
             showNext()
         } else {
             state = .Ready
         }
     }
    
    }
    
    func buttonTapped() {
     if state == .Ready {
        showNext()
     } else {
        state = .ShowNext
     }
    }