Search code examples
iosswiftaws-amplify

Cannot reload tableview within the amplify.api.query function


I am using Amplify to load data to my app. When I load a paginated list, I'm appending elements from a stored list onto my data model array. However, as the loading of the elements takes a bit of time, I either have to call tableView.reloadData() at the end of the amplify.api.query function in a completion handler or call tableView.reloadData() directly after I call events.append() within the amplify.api.query function. However, amplify.api.query neither has a completion handler nor lets me put tableView.reloadData() within the function itself, as every time I try to and I run the app, an error pops up saying that "UITableView.reloadData() must be used from main thread only." I want the tableview to load upon the UIViewController's startup. How should I do this?

func listFirstPage(finished: () -> Void) {

        Amplify.API.query(request: .paginatedList(Items.self, where: nil, limit: 1000)) { item in
            switch item {
            case .success(let result):
                switch result {
                case .success(let items):
                   
                    self.currentPage = items
                    self.events.append(contentsOf: items)
                    print(self.items)
                    self.AddItemTableView.reloadData()
                    
                case .failure(let error):
                    print("Got failed result with \(error.errorDescription)")
                }
            case .failure(let error):
                print("Got failed event with error \(error)")
            }
        }
        
          
    }

Solution

  • Do

    DispatchQueue.main.async {
       self.AddItemTableView.reloadData()
    }