Search code examples
swiftprintingclosures

Can't fetch data from API Closure


I am a beginner in Swift. I am trying to make app to fetch data from a Django server, but I'm stuck in fetch data from Closure, my code is as below:

var datasource: [Vender] = []

override func vieDidLoad() {
   super.viewDidLoad() 
   loaddata()
   print(datasource) //#1 print
}
 
func loadata(){ 
    VenderAPI(method: "GET", endpoint: "vender", APIportocol: Vender(), index: "") {
    Result in 
      switch Result {
        case .failure(let error):
          print(error.localizedDescription)
        case .success(let APIdata):
          for data in APIdata {
            self.datasource.append(data)
         }
     }
  print(self.datasource) //#2 print
}

My question is, I can get #2 print (correct data and format from server), but not #1 print (always empty). Can somebody help me? I will so appreciate.


Solution

  • as @Larme mentioned, you need to deal with the asynchronous function. Read-up about it. Try this approach:

    override func viewDidLoad() {
        super.viewDidLoad()
        loaddata() { done in  // <--- here
            print(datasource) // print when all work is done
        }
    }
     
    func loadata(completion: @escaping(Bool) -> ()) {  // <--- here
        VenderAPI(method: "GET", endpoint: "vender", APIportocol: Vender(), index: "") {
            result in
            switch result {
            case .failure(let error):
                print(error.localizedDescription)
            case .success(let APIdata):
                for data in APIdata {
                    self.datasource.append(data)
                }
            }
            completion(true)  // <--- here
        }
    }